You are on page 1of 63

Chapter 03

printf()와 데이터 형식
printf and Data Types
1. printf( ) 함수의 기본 형태 Basic form of printf funtion

2. printf( ) 함수의 서식 지정 Formatting the printf function

3. 변수의 이해 Understanding Variables

4. 데이터 형식과 배열 Data types and arrays


1. printf( ) 함수의 기본 형태 Basic form of printf function

 printf( ) 함수의 기본 사용법 Basic usage of printf function


 printf( ) 함수: 화면(모니터)에 큰따옴표(“ “) 안의 내용을 출력하라는 의

 printf () function: prints the contents of the double quotation mark ("") on
the screen (monitor)
1. printf( ) 함수의 기본 형태 Basic form of printf function

 printf( ) 함수의 기본 사용법 Basic usage of printf function


 숫자 출력 예시 Numeric output example

• 첫 번째 printf(“100”)의 결과인 100은 ‘글자 100(일영영)’. printf( )는 큰따옴표


안에 있는 것을 무조건 글자로 취급한다.
• The result of the first printf ("100"), 100, is the letter 100. printf () treats
anything in double quotes as an unconditional letter.
• 두 번째 printf(“%d”, 100)의 결과인 100은 ‘숫자 100(백)’. 서식(%d)이 지정된
숫자는 그대로 숫자의 의미를 지니기 때문이다.
• The result of the second printf ("% d", 100), 100, is the number 100. This is
because the number (% d) specified has the meaning of a number.
1. printf( ) 함수의 기본 형태 - [기본 3-1] printf( ) 함수 사
용예①

01 #include <stdio.h>
02
03 int main( )
04 {
05 printf("100+100"); ---모두 글자로 취급한다.
06 printf("\n");
07 printf("%d", 100+100); --- 숫자를 계산해서 결과를 출력한다.
08 printf("\n");
09 }
1. printf( ) 함수의 기본 형태 Basic form of printf function

 printf() 함수 사용 예 1 Using the printf () Function Example 1


• printf( ) 함수의 서식 앞에는 %가 붙는다.
• The format of the printf () function is prefixed with%.
• 7행의 %d는 정수(decimal)를 의미한다.
• Line 7% d means an integer (decimal).
• 서식의 개수와 큰따옴표 뒤에 나오는 숫자(또는 문자)의 개수가 같아야 한다.
• The number of forms (or characters) after the double quotation marks
must be the same.
1. printf( ) 함수의 기본 형태 - [기본 3-2] printf( ) 함수 사
용예②

01 #include <stdio.h>
02
03 int main( )
04 {
05 printf("%d", 100, 200); ---%d는 1개, 숫자는 2개이다.
06 printf("\n");
07 printf("%d %d", 100); ---%d는 2개, 숫자는 1개이다.
08 printf("\n");
09 }
1. printf( ) 함수의 기본 형태 Basic form of printf function

 printf() 함수 사용 예 2 Example 2 Using the printf () Function


• 5행은 %d가 하나인데 숫자가 2개(100, 200), 7행은 %d가 2개인데 숫자는 하나(100)이
다. 숫자 2개를 출력하려면 %d 2개, 숫자 2개 필요. 5행은 다음과 같이 고쳐야 한다.
• Line 5 has a single% d with two numbers (100, 200), seven lines with two %d, and
the number is one (100). To print two digits, you need two %d and two digits. Line
5 should be modified as follows.

• 7행은 두 번째 %d에 대응할 숫자가 없어 정수형 기본인 0이 출력되므로 %d를 하나


삭제해야 한다.
• Line 7 has a number corresponding to the second %d, so 0 is output as the integer
type.
1. printf( ) 함수의 기본 형태 - [기본 3-3] 서식을 사용한 출
력예①

01 #include <stdio.h>
02
03 int main( )
04 {
05 printf("%d / %d = %d", 100, 200, 0.5); ---%d가 3개, 숫자도 3개이다.
06 printf("\n");
07 }
1. printf( ) 함수의 기본 형태 Basic form of printf function

 정수 외에 자주 사용되는 서식 Frequently used forms besides integers


 서식을 사용한 출력 예 1 Example Output Using Forms 1
• 100/200의 계산 결과가 0.5가 아닌 0인 이유는 0.5는 실수(소수점이 있는 수)인데 보여
주는 방식이 정수(소수점이 없는 수)이기 때문이다. 결과를 출력하는 서식에 정수형
(%d)을 사용.
• The reason why the calculation result of 100/200 is 0 instead of 0.5 is because 0.5 is a real
number (the number with a decimal point) but the way of showing is an integer (a number
without a decimal point). Use an integer (% d) as the format for outputting the result.
1. printf( ) 함수의 기본 형태 Basic form of printf function

• printf( )에서 사용할 수 있는 대표적인 서식의 종류


• Typical types of formatting available in printf ()

• 문자는 ‘ ’ 안에 한 글자만 들어 있어야 하고 문자열은 “ ” 안에 한 글자 이상


이 들어 있어야 한다.
• Characters must contain only one character in '' and strings must contain
more than one character in "".
1. printf( ) 함수의 기본 형태 - [응용 3-4] 서식을 사용한 출
력예②

01 #include <stdio.h>
02
03 int main( )
04 {
05 printf("%d / ___①____ = ___②____ \n", 100, 200, 0.5); --- 정수 2개와 실수 1개를 출력한다.
06 printf(" ___③____ %c \n", 'a', 'K'); --- 문자 2개를 출력한다.
07 printf("%s %s \n", "안녕", "c 언어"); --- 문자열 2개를 출력한다.
08 }
1. printf( ) 함수의 기본 형태 Basic form of printf function

 서식을 사용한 출력 예 2 Example Output Using Forms 2


• 0.5 출력하기 위해 5행에서 %f 사용했지만 결과는 0.5가 아닌 0.500000이다.
• I used %f on line 5 to output 0.5, but the result is 0.500000 instead of 0.5.
• 같은 값이기는 하지만 한눈에 들어오지 않는다(이 장의 후반부에서 이에 대
해 자세히 살펴보겠다).
• It is the same value, but it does not come at a glance (I'll take a closer
look at it later in this chapter).
2. printf( ) 함수의 서식 지정 - [기본 3-5] 다양한 서식 활용 예 ①

01 #include <stdio.h>
02
03 int main( )
04 {
05 printf("%d\n", 123);
06 printf("%5d\n", 123); --- 정수형 서식을 활용한다.
07 printf("%05d\n", 123);
08
09 printf("%f\n", 123.45);
10 printf("%7.1f\n", 123.45); --- 실수형 서식을 활용한다.
11 printf("%7.3f\n", 123.45);
12
13 printf("%s\n", "Basic-C");
--- 문자열형 서식을 활용한다.
14 printf("%10s\n", "Basic-C");
15 }
2. printf( ) 함수의 서식 지정 Formatting the printf () function

 자릿수를 맞춘 출력 Output with aligned digits


• 정수형 데이터를 출력하려면 5~7행은 [그림 3-3]과 같이 나타낼 수 있다.
• To output integer data, lines 5 to 7 can be shown as [Figure 3-3].
2. printf( ) 함수의 서식 지정 Formatting the printf () function

 자릿수를 맞춘 출력 Output with aligned digits


• 실수형 데이터 서식 지정은 [그림 3-4]와 같다. 두 번째의 %7.1f는 소수점을 포함한 전
체 자리인 일곱 자리 확보한 후에 소수점 아래는 한 자리만 차지한다는 의미. 소수점
위 정수 부분은 다섯 자리가 된다.
• The real format data formatting is shown in [Figure 3-4]. The second,% 7.1f, means
that it occupies one digit below the decimal point after seven digits, which is the
whole digit including the decimal point. The integer part above the decimal point is
five digits.
2. printf( ) 함수의 서식 지정 Formatting the printf () function

• 문자열형 데이터 서식은 오른쪽에 맞춰서 출력된다.


• The string data format is output to the right.
2. printf( ) 함수의 서식 지정 Formatting the printf () function

 다양한 기능의 서식 문자 Variety of formatting characters


• 서식 문자는 앞에 반드시 ‘ \’가 붙는다. 이런 문자를 탈출(escape) 문자라고도 한다.
Format characters must be preceded by a '\'. These characters are also called
escape characters.
2. printf( ) 함수의 서식 지정 - [기본 3-6] 다양한 서식 활용 예 ②

01 #include <stdio.h>
02
03 int main( )
04 {
05 printf("\n줄 바꿈\n연습 \n");
06 printf("\t탭키\t연습 \n");
07 printf("이것을\r덮어씁니다 \n");
08 printf("\a\a\a삐소리 3번 \n"); --- 컴퓨터에 따라서 소리가 한 번만 날 수도 있다.
09 printf("글자가 \"강조\"되는 효과 \n");
10 printf("\\\\\\ 역슬래시 세개 출력 \n");
11 }
2. printf( ) 함수의 서식 지정 Formatting the printf () function

• 6행의 \t는 [Tab]에 지정된 만큼의 간격을 벌린다.


• In line 6, \ t makes a space as specified in [Tab].
• 7행에서는 ‘이것을’이라는 문구를 출력했다가 \r을 만나서 다시 처음 위치로
돌아가 ‘덮어씁니다’를 출력하므로 ‘이것을’이 지워져서 보이지 않는다.
• Line 7 prints the phrase 'this', then returns to the first position after seeing
\ r and 'overwrites', so 'this' is erased and not visible.
• 8행에서는 ‘삐삐삐’ 소리를 낸다.
• On the 8th line, BEEP sounds.
• 9행에서는 강조라는 단어 앞뒤에 “ ”를 출력한다.
• In line 9, "" is printed before and after the word emphasis.
• 10행은 역슬래시(\) 하나를 출력하려면 \를 두 번 입력해야 한다는 것을 보
여준다.
• Line 10 shows that you need to type \ twice to print one backslash (\).
3. 변수의 이해 Understanding Variables

 변수의 선언 Declaring Variables


• 소수점이 없는 값과 소수점이 있는 값을 담는 변수 선언
• Declare a variable that contains a value with no decimal point and a
decimal point
3. 변수의 이해 Understanding Variables

 변수의 선언 Declaring Variables


• 변수 a보다 변수 b 크기가 더 큰 것은 정수형 변수와 실수형 변수의 크기가 다르기 때
문(데이터 형식의 크기는 뒤에서 살펴보겠다).
• The variable b is larger than the variable a because the size of the integer variable
is different from the size of the real variable (the size of the data format will be
described later).
• 변수 종류가 같으면 변수를 개별적으로 선언해도 되고 콤마(,)를 사용하여 연속 선언해
도 된다.
• If the variables are the same, you can declare them individually or you can declare
them consecutively using a comma (,).
3. 변수의 이해 Understanding Variables

 변수에 값을 담는 방법 How to put a value into a variable


 기본적인 값의 대입 Assigning a value to a base value
3. 변수의 이해 Understanding Variables

 변수에 값을 담는 방법 How to put a value into a variable


 기본적인 값의 대입 Assigning a value to a base value
• 정수형 변수 a와 실수형 변수 b를 선언하고 변수에 값을 넣는 방법
• How to declare an integer variable a and a real variable b and put a value in the
variable

• 변수 선언 후에 값을 대입해도 되고 변수 선언과 동시에 값을 대입해도 된다.


• You can assign a value after the variable declaration, or you can assign the value at
the same time as the variable declaration.
• 변수 선언과 동시에 값을 대입하면 프로그램이 좀 더 간결해진다.
• Assigning values at the same time as variable declarations makes the program
more compact.
3. 변수의 이해 Understanding Variables

• 변수 a, b가 모두 정수형 변수라면 한 줄로 표현 가능
• If variables a and b are all integer variables, they can be expressed in one line

 지정된 데이터 형식과 다른 값을 변수에 대입하는 경우


 If you assign a variable to a value that is different from the specified data
type
3. 변수의 이해 - [기본 3-7] 변수에 값 대입 예

01 #include <stdio.h>
02
03 int main( )
04 {
05 int a; --- 정수형 변수 a를 선언한다.
06 float b; --- 실수형 변수 b를 선언한다.
07
08 a = 123.45; --- 정수형 변수에 실수를 대입한다. ← 바람직하지 않다.
09 b = 200; --- 실수형 변수에 정수를 대입한다. ← 바람직하지 않다.
10
11 printf ("a의 값 = = > %d \n", a);
12 printf ("b의 값 = = > %f \n", b);
13 }
3. 변수의 이해 Understanding Variables

• 실행은 되었지만 정수형 변수 a에 대입한 실수의 일부분만 출력되었다.


• It was executed, but only a part of the real number assigned to the integer variable
a was output.
• 실수(123.45)를 대입해도 변수가 정수형이므로 소수점 아래가 떨어져 정수(123)만 저
장된다.
• Even if the real number (123.45) is assigned, since the variable is an integer type,
the decimal point falls below the decimal point and only integer 123 is stored.
3. 변수의 이해 Understanding Variables

• 실수형 변수에 정수를 담은 경우 처리 방식([그림 3-9])


• If a real variable contains an integer, the processing method
([Figure 3-9])

• 9행 수정 방안
3. 변수의 이해 - [응용 3-8] 변수에 변수 대입 예 ①

01 #include <stdio.h>
02
03 int main( )
04 {
05 int a, b; --- 정수형 변수 2개를 선언한다.
06 float c, d;
--- 실수형 변수 2개를 선언한다.
07
08 a = 100; --- a에 정수 100을 대입한다.
09 ___①____
--- b에 a 값을 대입한다.
10
11 c = 111.1f; --- c에 실수 111.1을 대입한다.
12 ___②____ --- d에 c 값을 대입한다.
13
14 printf ("a, b의 값 = = > %d , %d \n", a, b);
15 printf ("c, d의 값 = = > %5.1f , %5.1f \n", c, d);
16 }
3. 변수의 이해 Understanding Variables

 다양한 값의 대입 방법 Assignment of various values


• 정수형 변수 a에 값 대입, 정수형 변수 b에 값 대신 a 대입시 처리 방식
• Assigning a value to an integer variable a, processing a value when a is
substituted for an integer variable b
3. 변수의 이해 - [응용 3-9] 변수에 변수를 대입하는 예 ②

01 #include <stdio.h>
02
03 int main( )
04 {
05 int a, b, c, d;
06
07 a = 100 + 100; --- a에 두 수의 계산 결과를 대입한다.
08 b = a + 100; --- b에 변수와 수의 계산 결과를 대입한다.
09 c = a + b - 100; --- c에 변수와 수의 계산 결과를 대입한다
10 ___①____ --- d에 a, b, c의 덧셈 결과를 대입한다.
11 printf ("a, b, c, d 의 값 = = > %d, %d, %d, %d \n", a, b, c, d);
12
13 ___②____ --- a, b, c, d에 모두 100을 대입한다(한 문장으로 처리한다).
14 printf ("a, b, c, d 의 값 = = > %d, %d, %d, %d \n", a, b, c, d);
15
16 a = 100;
17 a = a + 200; --- a에 자신의 a 값과 200을 더한 값을 다시 대입한다
18 printf ("a 의 값 = = > %d \n", a);
19 }
3. 변수의 이해 Understanding Variables

• 7행은 연산 결과를 변수에 대입하는 방식


• Line 7 is the method of assigning the operation result to the variable
3. 변수의 이해 Understanding Variables

• 8행은 변수와 숫자 계산 결과를 대입하는 방식


• Line 8 is a method of assigning the results of variable and
numerical calculations
3. 변수의 이해 Understanding Variables

• 13행은 연속된 값을 대입하는 방식


• Line 13 is a way to assign consecutive values
3. 변수의 이해 Understanding Variables

• 17행은 자신의 값으로 연산 후 다시 자신에게 대입하는 방식


• The 17th row is computed with its own value and then assigned to itself again
3. 변수의 이해 Understanding Variables

 대입 연산자와 변수의 위치
 Location of assignment operators and variables
• 규칙1: 대입 연산자(=)를 사용하면 오른쪽의 것이 왼쪽에 대입된다.
• Rule 1: Using the assignment operator (=), the right side is assigned to the left side.
• 규칙2: 대입 연산자(=)의 오른쪽에는 상수(숫자), 변수, 계산값이 모두 올 수 있다.
• Rule 2: The assignment operator (=) can be a constant (number), a variable, or a
calculated value to the right.
4. 데이터 형식과 배열 Data types and arrays

 비트, 바이트, 진수 Bits, Bytes and Binary


 비트 Bit
• 컴퓨터에서 표현하는 가장 작은 단위로, 0과 1만 존재.
• It is the smallest unit represented by a computer, and only 0 and 1 exist.
• 비트는 전기스위치와 비슷한 개념으로 0(OFF)과 1(ON)만 존재함.
• Bit is similar to electric switch, and there are only 0 (OFF) and 1 (ON).
4. 데이터 형식과 배열 Data types and arrays

 진수Binary
• 2진수 : 표현 가능한 숫자 0, 1
• Binary Number, 0 1
• 10진수 : 표현 가능한 숫자 0~9
• Decimal Number, 0 ~ 9
• 16진수 : 표현 가능한 숫자 0~9, A~F
• Hexadecimal 0~9, A~F
• 진수를 구분하여 표기하는 방법
– 2진수 : 102
– 10진수 : 1010
– 16진수 : 1016
4. 데이터 형식과 배열 Data types and arrays

 바이트 Byte
• 비트 8개가 합쳐진 단위 Unit of 8 bits combined
4. 데이터 형식과 배열 Data types and arrays

 숫자형 데이터 형식 Numeric data types


 소숫점이 없는 정수형 Integer without a decimal point
4. 데이터 형식과 배열 Data types and arrays

 숫자형 데이터 형식 Numeric data types


• 나이, 연도, 통장 잔고 등은 소수점을 넣지 않으므로 정수형으로 사용
• Age, year, bankbook number, etc. do not include decimal point, so use it as
integer type.
– 마이너스 값이 있을 수 없는 나이나 연도에는 unsigned int나 unsigned short 사용
– Use unsigned int or unsigned short for years or years that can not have negative values.
– 나이나 연도의 최댓값이 unsigned short의 최대 크기인 65535를 절대 넘지 않으므로 unsigned int보다 저장 공간을
더 적게 사용하는 unsigned short 사용하는 것이 더 효율적임.
– It is more efficient to use unsigned short, which uses less storage space than unsigned int, since the maximum
value of year or year never exceeds 65535, the maximum size of unsigned short.

• 정수끼리 연산을 수행하면 결과도 정수가 된다.


• When performing an operation between integers, the result is also an integer.
• 숫자 연산 시 실수가 하나라도 들어가면 결과는 실수가 된다.
• If you enter a real number in a numeric operation, the result is a real number.
4. 데이터 형식과 배열 - [기본 3-10] 소수점이 없는 정수형 사용 예

01 #include <stdio.h>
02
03 int main( )
04 {
05 int a=100, b=200; --- 정수형 변수 a와 b에 값을 지정한다.
06 float result; --- 실수형 변수 result를 선언한다.
07
08 result = a / b; --- a를 b로 나눈 결과를 실수형 변수 result에 대입한다.
09
10 printf ("%f \n", result);
11 }
4. 데이터 형식과 배열 Data types and arrays

 소수점이 있는 실수형 Real type with decimal point


4. 데이터 형식과 배열 Data types and arrays

 문자형 데이터 형식 Character data type


 아스키 코드 ASCII CODE

• 숫자를 이용해서 문자를 표현하도록 하려면 숫자를 문자에 연결(mapping)시


키는 것이 유일한 방법입니다. 연결하는 방법과 표준은 다양하게 존재하는데,
C언어는 '미국 표준 협회(ANSI: American National Standards Institute)'에 의
해서 제정된 '아스키(ASCII: American Standard Code for Information
Interchange) 코드'라는 표준을 선택해서 문자를 표현합니다. 그리고 이러한
아스키 코드는 알파벳과 일부 특수문자를 포함하여 총 128개의 문자로 이뤄
져 있습니다.
• 참고로 아스키는 7비트 혹은 8비트로도 표현할 수 있는데, 8비트 아스키의
경우,
• 제어문자를 포함하여 총 256개를 표현할 수 있습니다.
• 밑의 표는 7비트 아스키 코드 표입니다.
4. 데이터 형식과 배열 Data types and arrays

• 숫자 0은 48, 대문자 A는 65, 소문자 a는 97 등은 알아두면 편함.


• The number 0 is 48, the uppercase A is 65, and the lowercase a is 97.
• C 언어에서는 숫자를 문자로도 표현함.
• In C, numbers are also represented by letters.

 한 글자를 뜻하는 문자형 Character type that means one letter


4. 데이터 형식과 배열 - [기본 3-12] 문자형 변수 사용 예 ①

01 #include <stdio.h>
02
03 int main( )
04 {
05 char a, b, c; --- 문자형 변수 3개를 선언한다.
06
07 a = 'A'; --- 문자형 변수 a에 'A'를 대입한다.
08
09 printf(" %c \n", a); --- 문자형 변수 a를 문자형과 정수형으로 출력한다.
10 printf(" %d \n", a);
11
12 b = 'a'; ---문자형 변수 b에 'a'를 대입한다.
13 c = b + 5; ---문자형 변수 b에 5를 더해서 문자형 변수 c에 대입한다.
14 printf(" %c \n", b);
15 printf(" %c \n", c);
16
17 c = 90; ---문자형 변수 c에 숫자 90을 대입한다.
18 printf(" %c \n", c);
19 }
4. 데이터 형식과 배열 Data types and arrays

• 5행에서 문자형 변수 a, b, c 선언
• Declare character variable a, b, c in line 5
• 7행에서 변수 a에 문자 ‘A’ 대입, 9행에서 문자형으로 출력
• In the line 7, assign the letter 'A' to the variable a,
• 10행에서 문자형 변수 a를 정수형으로 지정하기 ‘65’ 출력
• Specify character type variable a as integer type in line 10 Output '65'
‘A’와 65는 동일한 값이지만 어떤 출력 서식을 사용하느냐에 따라 다른 값
출력
'A' and 65 are the same value, but depending on which output format
you are using, output a different value
4. 데이터 형식과 배열 Data types and arrays

 여러 글자가 모인 문자열과 배열 Strings and arrays of multiple characters

 문자열의 기본 형식 Default type of string


• 문자열은 한 문자가 여러 개 이어진 것. A string is a string of characters.
– ‘Hanbit’이라는 글자의 저장 구조 The storage structure of the character 'Hanbit'

• 널(null) 문자 : \0 The null character: \ 0


– 문자열의 끝을 알려주는 역할 The role of telling the end of a string
– 화면에 출력되지 않음 No output on screen

• 문자열은 문자 배열을 사용 String uses character array


4. 데이터 형식과 배열

• strcpy( ) 함수로 문자열 대입 Assign a string to the strcpy () function


– str 배열에 ‘Basic’이라는 글자 5개의 문자열 대입 Assign 5 strings of 'Basic' to the str array

– 출력 print
4. 데이터 형식과 배열 - [기본 3-14] 문자열 형식 사용 예 ①

01 #include <stdio.h>
02 #include <string.h>
03
04 int main( )
05 {
06 char str1[10]; ---문자형 배열 str1과 str2를 선언한다.
07 char str2[10];
08 char str3[10] = "CookBook"; ---문자형 배열 str3을 선언함과 동시에 문자열을 대입한다.
09
10 strcpy(str1, "Basic-C"); ---str1에 문자열을 대입한다.
11 strcpy(str2, str3); ---str3의 값을 str2에 복사한다.
12
13 printf("str1 = = > %s \n", str1); ---문자형 배열 str1, str2, str3을 출력한다.
14 printf("str2 = = > %s \n", str2);
15 printf("str3 = = > %s \n", str3);
16 }
4. 데이터 형식과 배열 - [응용 3-15] 문자열 형식 사용 예 ②

01 #include <stdio.h>
02
03 int main( )
04 {
05 char str[10] = "0123456789"; ---열 자리의 str 배열에 글자 10개를
대입한다.
06
07 printf("str = = > %s \n", str); ---str의 내용을 출력한다.
08
09 str[0] = 'I';
---str 배열에 글자 6개와 널 문자를 입력한다.
10 str[1] = 'T';
11 str[2] = 'C';
12 str[3] = 'o';
13 str[4] = 'o';
14 str[5] = 'k';
15 str[6] = '\0';
16
17 printf("str = = > %s \n", str); ---str의 내용을 출력한다.
18 printf("str[7] = = > %c \n", ___①____ ); ---str[7]의 한 글자를 출력한다.
19 printf("str[50] = = > %c \n", ___②____ ); ---str[50]의 한 글자를 출력한다.
20 }
4. 데이터 형식과 배열

• 5행
– str 배열을 선언하면서 문자열 대입 Assigning a string while declaring str array
– 널 문자가 없기 때문에 출력 시 문제 발생 There is no null character, so there is a problem in output

• 9행~15행의 str 배열 Str array from row 9 to row 15


[예제모음 04] 정수형을 출력하는 프로그램
[예제모음 04] 정수형을 출력하는 프로그램

01 #include <stdio.h>
02
03 int main( )
04 {
05 int data; ---정수형 변수를 선언한다.
06
07 printf("정수를 입력하세요 = = > ");
08 scanf("%d", &data); ---키보드로 정수를 입력받는다.
09
10 printf("10진수 = = > %d \n", data); ---10진수(%d), 16진수(%X), 8진수(%o)를 출력한다.
11 printf("16진수 = = > %X \n", data);
12 printf("8진수 = = > %o \n", data);
13 }
[예제모음 05] 입력하는 정수의 진수 결정
[예제모음 05] 입력하는 정수의 진수 결정

01 #include <stdio.h>
02
03 int main( )
04 {
05 int type, data;
06
07 printf("입력진수 결정 <1>10 <2>16 <3>8 : ");
08 scanf("%d", &type); ---키보드로 1~3 중 하나를 입력받는다.
09
10 printf("값 입력 : ");
11
12 if(type = = 1) ---입력값이 1이면 10진수를 입력받는다.
13 { scanf("%d", &data); }
14
15 if(type = = 2) ---입력값이 2이면 16진수를 입력받는다.
16 { scanf("%x", &data); }
17
18 if(type = = 3) ---입력값이 3이면 8진수를 입력받는다.
19 { scanf("%o", &data); }
20
21 printf("10진수 = = > %d \n", data); ---입력받은 data 값을 10진수, 16진수, 8진수로 변환하여
22 printf("16진수 = = > %X \n", data); 출력한다.
23 printf("8진수 = = > %o \n", data);
24 }
[예제모음 06] 데이터형의 크기 확인
[예제모음 06] 데이터형의 크기 확인

01 #include <stdio.h>
02
03 int main( )
04 {
05 printf("int 형의 크기\t\t\t = = > %d\n", sizeof(int)); --sizeof( ) 함수로 각 데이터형의
06 printf("unsigned int 형의 크기\t\t = = > %d\n", sizeof(unsigned int)); 크기(바이트 수)를 출력한다. 이때
컴파일러에 따라서 long double
07 printf("short 형의 크기\t\t\t = = > %d\n", sizeof(short)); 형은
08 printf("unsigned short 형의 크기\t = = > %d\n", sizeof(unsigned short)); 16바이트 크기일 수도 있다.
09 printf("long int 형의 크기\t\t = = > %d\n", sizeof(long int));
10 printf("unsigned long int 형의 크기\t = => %d\n", sizeof(unsigned long int));
11 printf("float 형의 크기\t\t\t = = > %d\n", sizeof(float));
12 printf("double 형의 크기\t\t = = > %d\n", sizeof(double));
13 printf("long double 형의 크기\t\t = = > %d\n", sizeof(long double));
14 printf("char 형의 크기\t\t\t = = > %d\n", sizeof(char));
15 printf("unsigned char 형의 크기\t\t = = > %d\n", sizeof(unsigned char));
16 }
[예제모음 07] 입력된 문자열을 반대 순서로 출력
[예제모음 07] 입력된 문자열을 반대 순서로 출력

01 #include <stdio.h>
02
03 int main( )
04 {
05 char str[10]= " "; ---문자열을 입력받을 str 배열을 준비한다.
06 int i; ---첨자를 준비한다.
07
08 printf("문자열을 입력 = = > ");
09 scanf("%s", str); ---문자열을 입력받는다.
10
11 for(i = sizeof(str) - 1; i >= 0; i- -)
---str 배열에 들어 있는 문자열을 맨 뒤의 str[9]부터 str[0]까지
12 { 출력한다. 즉 입력한 순서의 반대로 출력되는 것이다.
13 printf ("%c", str[i]);
14 }
15 printf("\n");
16 }
[3장. 요약]

1 printf( ) 함수
➊ 모니터에 무언가를 출력하는 역할.
➋ 형식: printf("서식", 인자 …)
➌ 정수는 %d, 실수는 %f, 문자는 %c, 문자열은 %s 서식 사용.

2 printf( ) 함수의 서식
➊ %5d는 다섯 자리로 정수 출력.
➋ %7.3f는 전체 일곱 자리에 소수점 아래 세 자리의 실수 출력.
➌ \n은 새로운 줄로 이동, \t는 다음 탭으로 이동, \\는 \를 출력하는 등의 다양한 서식
문자 존재.

3 변수에 값을 대입하는 방법
• ‘10=100’처럼 왼쪽에 상수가 오면 안 되고 ‘a=100’과 같이 왼쪽에 변수가 와야 한다.
• 오른쪽에는 상수, 변수, 계산값 등 무엇이든지 올 수 있다.
[3장. 요약]

4 데이터 형식
❶ 컴퓨터에서 내부적으로 사용되는 것은 2진수, 2진수 네 자리를 묶은 것이 16진수.
➋ 정수 데이터 형식에는 short, int, long 등이 있으며 부호 없이 사용하려면 unsigned를
붙인다.
➌ 실수 데이터 형식에는 float, double 등이 있다.
➍ 한 글자를 저장하는 문자 데이터 형식에는 char, 여러 글자를 저장하기 위한 문자열
데이터 형식은 문자 데이터 형식의 배열 사용. 단, 문자열의 끝을 표시하는 널 문자를 저
장하기 위해 ‘실제 문자열 길이+1’로 크기 선언.
감사합니다.

You might also like