C Programming
Data types and variables
(chapter 2)
Dept. of AI-Software, Gachon
Univ.
Hyungchul Lee
In this
lecture
Variables, data
types
Quiz
1-1
Recall the
simple C
Program
#include
void main<stdio.h> Data
() types
{ int num1, num2, Variabl
num3; es
printf (“\n Please type an integer: \
n”);
scanf (“%d”, /* read an integer */
printf (“\n Please type another integer: \
&num1);
n”); scanf (“%d”, &num2);
num3 = num1 + num2;
Assignment
printf (“result = %d”, num3);
Variables, Data
Types,
Assignment
num1, num2,
num3
variables
int, float
data types
iresult = iresult +
747;
assignment
Variable
s
Variabl
es
A Variable Is a Symbolic Name
for a Computer Memory
Location That Holds Some Data.
Variables naming
rules
Variable Name
starts with an English letter or _
followed by English letters, digits, or _
upper case letter and lower case letter for
the same letter are different.
must Not be a C reserved word
break, case, char, const, continue, do,
double, else, float, for, if, int, return,
switch, while,…
should not be longer than 20
characters
should be mnemonic( 기억을 돕는 )
Exampl
es
Good
firstNum,
secondNum,…
_first_num,..
Sum100,
Bad
John, good, bad,…
IhateBillGates,..
Wrong
$firstNum,
5numbers,…
Variable
Declarations
int i;
int j;
int k;
float
F;
float
C;
float
F2C;
Variable
Declarations
int i, j, k;
float F, C, F2C,
C2F;
Memory
Allocation
memory
&%$ #!+ *^)!
i j FC
Variable
Declarations
Variabl
es
A Data Type Must Be Specified
for Each Variable.
All Variables and Their Data Types
Should Be Declared Together At the
Start of a Program.
Initialization is important.
int numOne = 15;
C
Constant
Values That Never Change
s Allocated, and Value Stored.
Memory Automatically
Number (different from algebra)
integer: 345, 21, -12, 0, …
real (floating-point number)
3.14, 6.0, 0.0, -12.0
3.14f, 6.0f, 0.0f, - Either
12.0f OK
Characters
‘a’, ‘b’,…, ‘2’, ‘&’,…
Refer to ASCII
code
Character Strings
“hello”, “number”,
…
Data
type
Data Types
(1)
Integer ( 정
수)
Data type Memory
size
Ranges Conversion
character
short signed 2 byte* -32,768 ~ 32,767 %hd
unsigned 0 ~ 65,535 %hu
int signed 4 byte(2byte) -2,147,483,648 ~ %d
2,147,483,647
unsigned 0 ~ 4,294,967,295 %u
long signed 4 byte -2,147,483,648 ~ %ld
2,147,483,647
unsigned 0 ~ 4,294,967,295 %lu
char signed 1 byte -128~+127 %c
• Memory size is different depending on0compiler,
unsigned ~ 255
CPU etc. long long 8
• 32 bit CPU, visual C++ compiler case byte
printf
function
Printf : print formatted
Specifies a method for rendering an
arbitrary number of varied data type
parameters into a string
provides a description of the output
marked by % escape characters
specify both the relative location and
the type of output
printf
function
Example of
%i development
‣ Disable SDL(Securitye
Lifecycle)
Compile error!! (in Visual Studio Community
2022)
• 마이크로소프트에서는 scanf( ) 함수 대신 보안이 강화된 scanf_s( ) 함수의 사용을 적극 권장
• scanf( ) 는 overflow 시 넘어가는 메모리 영역에 write 하여 다른 영역을 침범
• scanf( ) 와 scanf_s( ) 함수의 기능은 동일
• scanf 경고 메시지를 없애기
솔루션탐색기 → 사용자 프로젝트 → 오른쪽마우스 클릭 : 속 성 → C / C + + →
일반 : SDL 검사 : 아니요
Data Types
(1)
Singed ( 부호있는 )vs unsigned ( 부호없는 )
Most significant bit (MSB, high-order
bit) = sign bit
"1" meaning negative -
"0" meaning positive +
sign bit
MSB LSB
1 0 0 0 0 0 0 0
Data Types
(1)
unsigned ( 부호없는 )
expressions
Representation of minus with
digits
MSB LSB
sign
1 bit0 0 0 0 0 0 0
Data Types
(1)
Signed( 부호있는 ) expression
How to express -10?
Assume that integer type
variable num
Data Types
(1)
For example 4 bit
representation
6(10) = 0110(2) 011 011
-6(10) 6 + (-6) = 0 101
+0
+? 0
0 000 000
-6(10) 1010(2) = - 0 0
6(10)
Data Types
(1)
1’s complement
Values to make all
digits
Ex) 110to +
1 001
= 111 6(10) = 0110(2)
2’s complement
-6?
1’s complement 1’s complement
+1 1001(2)
Ex) 110 + 010 2’s complement
1010(2) 1010(2) = -
= 1000 6(10)
0110(2)
+ 1010(2)
Quiz
2-1
1) What is the decimal number of
the binary number? (assume
unsigned
1 0 representation)
0 1 0 1 0 1
1280 0 16 0 4 0
1
128+16+4+1 =149
Quiz
2-2
2) Printf(“%d”,a
char
char a=202;
Printf(“%d”,a
a=128;
)? )?
Quiz
2-2
2) Printf(“%d”,a
char
char a=202;
Printf(“%d”,a
a=128;
)? 8 7 6 5 4 )?
3 2 1
128 64 32 16 8 4 2 1
1 0 0 0 0 0 0 0 -128
Signe 0 1 1 1 1 1 1 1 127
d
0 1 1 1 1 1 1 1 127
128 1 0 0 0 0 0 0 0 127+1 → -
? 128
0 1 1 1 1 1 1 1
202 1 0 0 0 0 0 0 0 127
127+1 → -
? 1 1 0 0 1 0 1 0 128
1100 1010 (-202) 202 -127 =
75
0011 0101 (1 의보수 ) -128 + 74 = -
0011 0110 (2 의보수 : 54
54)
Quiz
2-3
What are printed?
char a = -10;
unsigned char b = a;
printf(" d d", a,
10b);
= 0000 1010
-10?
1’s complement of 10 → 1111
0101
2’s complement of 10 → 1111
0110 →
27+26+25+24+22+21 =
Data Types
(2)
Floating-Point
What is floating point?
Formulaic representation that
approximates a real number so as to
support a trade-off between range and
precision
A number's radix point (decimal point or
binary point) can "float“, it means that It
can be placed anywhere relative16 tobit
the 16 bit
significant digits of the number. (2 byte) (2 byte)
Why do we need this? 123 456
Limitation of fixed point expression
Ex) 123.456 with 32 bit (4 byte) limit
Fixed point
Data Types
(2)
Floating-Point (float :
sig
n 32bit)
1 8 bit
exponent
23 bit mantissa
n = s x 1.m x 2(e -127)
Floating point (IEEE
standard)
Data Memor Exampl Ranges Precisio Conversio
type y e n n
size character
float 4 byte 9.234f 1.4e-38~ 3.4e+38 6 %f
double 8 byte 9.234 -4.9e- 15 %lf
324~1.7e+308
long 8 byte 9.234l -4.9e- 18 %Lf
doubl 324~1.7e+308
e
Data Types
(2)
Example
Expression with floating point of
10.25 10.25(10) ➔
Convert to1010.01 ➔ 1010.01(2)
binary digits:
1.01001 x 23
Shift point:
0 10 0 0 0 0 10 0 1 0 0 1
3+127=1 1.m 에서 소수점 아랫부분 작성
30
1000001
0
Data Types
(2)
Common
questions
n = s x 1.m x 2(e -127)
1.m?
move to 1.0 form instead of moving to 0.1
To prevent 1 unnecessary movement of
decimal point.
e-127?
To express fractional values
Data Types
(2)
To convert a decimal 0.35(10)XX (2)?
value to binary 0.35 x 2 = 0.70 ->
Multiply the value by
0
2 not greater than 1
Specify 0 if the 0.70 x 2 = 1.40
result is not -> 1
greater than 1 Greater than 1
Specify 1 if the
1.40 - 1 = 0.40
result is greater
: Subtract 1
than 1
if the result is greater 0.40 x 2 = 0.80
than 1, Subtract 1 -> 0
from the result not greater than 1
Repeat this process 0.80 x 2 = 1.60
until the result is 1
-> 1
Grater than 1
1.60 - 1 = 0.60
Algebraic
Expressions
Algebra C
999 + 777 999 +
777
765 – 563
765 -
3.14 x 89
563
89.75 ÷13.7
3.14 *
89
89.75 /
13.7
56 %
10
Data Types &
Algebraic
Expressions
Different Operations for
Different Data Types.
integer: +, -, *, /, %
float: +, -, *, /
Data Types &
Algebraic
+, -, * Expressions
If both operands are integers, the
result is an integer
If one operand is a float, the result is
a double.
/
If both operands are integers, the
result is an integer
15 / 2 -> 7 (fractional part is always
dropped)
%
Result is the remainder.
valid only for integer values
Definition
statement of
variables
Inform to the computer to reserve 4byte
memory
int 4
Ta
number; g bytes
Inform to the computer about the name of
variable
First byte is used to tag “number” variables
Definition
statement of
int variables
num1;
int
num2;
int
num3;
num1=1
0; Memor
num2=2
Variable y
name num num num
0; 1
10 2
20 3
50
Mem num3=5 165 254 300
address 2 8 0
0;
Assignme
nt
Assignme
X = Y;
nt
computes expression
Y
stores the result in X
Example
int principal;
float rate;
float interest;
principal = 1000;
rate = .035;
interest = principal *
rate;
Memor
y
memory
1000 #!+ 0.035 35.0
principal rate interest
Assignme
X = Y;
nt
X: Variable
Data type is specified by the programmer.
Value may be given at declaration.
Value may be computed.
Y: Expression
constant
variable
algebra expression
comparison expression
Data type is computed.
The Data Types of X and Y May Not Be
the Same.
Initialization of
Variables
(1/2)
floa avg, total;
t num_student
int s;
total =
40120;
avg total / num_students;
= /* num_students not initialized
*/
Memor
y
&%$ 40120 *^)!
avg total num_students
Initialization of
Variables
(2/2)
floa avg, total;
t num_students =
int 50;
total =
40120;
avg total / num_students;
= /* num_students initialized
*/
Memor
y
802.4 40120 50
avg total num_students
Data Type
Conversion
Implicit( 암시적 ) Conversion
Explicit( 명시적 ) Conversion
(Cast)
Implicit Data
Type
Conversion
On Assignment
data type of the expression on the right
of = is automatically converted to the
data type of the variable on the left of
=
Safe Conversion
int to float
Unsafe Conversion
float to int
Implicit
Conversion
floa avg, total;
t num_students,
int num_trunc;
total = 40120;
num_students = 50;
num_trunc =total /
num_students;
Explicit
Conversion
floa avg, total;
t num_students,
int num_trunc;
total = 40120;
num_students = 50;
num_trunc =(int)total /
num_students;
Writing a
program
Writing a C
Program
Determine Data to Store
determine types of the data
Declare Variables and Types of
the Data
Write Program Using the
Variables
Exercis
e1
Compute the Volume of a
Swimming Pool
Step 1: Variable Declaration
Step 2: Compute
Step 3: Print the Volume.
Exercis
e1
Compute the Volume of a
Swimming Pool
Step 1: Variable Declaration
What data are needed?
What are the data types?
Name the variables.
Step 2: Compute
Compute the volume
Store the volume.
Step 3: Print the Volume.
Solutio
#include n
<stdio.h> void
main ( )
{
float length,
width, height,
volume;
printf (“\n Please type the length: \n”);
scanf (“%f”, &length);
printf (“\n Please type the width: \n”);
scanf (“%f”, &width);
printf (“\n Please type the height: \n”);
scanf (“%f”, &height);
volume = length * width *
Exercis
e2
Compute the Volume of a Circular
Cylinder
Step 1: Variable Declaration
Step 2: Compute
Step 3: Print the Volume.
Exercis
e2
Compute the Volume of a Circular
Cylinder
Step 1: Variable Declaration
What data are needed?
What are the data types?
Name the variables.
Step 2: Compute
Compute the volume
Store the volume.
Step 3: Print the Volume.
Solutio
#include n
<stdio.h> void
main ( )
{
float radius,
height, volume;
printf (“\n Please type the radius: \n”);
scanf (“%f”, &radius);
printf (“\n Please type the height: \n”);
scanf (“%f”, &height);
volume = 3.14 * radius * radius *
height; printf (“volume = %f”,
volume);
Expressio
ns
Expressio
ns
Algebraic
Expression
Comparison
Expression
Comparison
Expressions
Math
C
34 > 21 34 > 21
iresult < iresult < 897
897 iresult ==
iresult = 200
200 iresult != 75
iresult ≠ 75 number <=
number ≤ 54.9
54.9 number >=
Result of a
Comparison
either True orExpression
False.
True ( not 0)
False ( 0 )
xx == y >=
> y (x
x < y y)
x != (x <=
y y)
Boolean
Operators
AND (&&), OR (||), NOT (!)
Each operand is an expression that
evaluates to
“True” or “False”
AND
“True” if and only if both operands evaluate
to “True”
OR
“True” if any one operand evaluates to
“True”
NOT
Exampl
es
(age == 22) && (GPA
< 3.5)
(GPA > 4.2) || (age <
19)
!(GPA > 4.2)
A: age = 22, GPA =
2.5
?
B: age = 25, GPA =
4.3
?
Exerci
#include se
<stdio.h> void
main ( )
{
/* read three integers N1 and N2, N3
and if first number is the biggest
number, print “num1 is the
biggest”
if not, print “num1 is not the biggest
number.”
*/
}
Solutio
#include n
<stdio.h> void
main ( )
{
int num1,
num2, num3;
printf (“\n Please type a number: \n”);
scanf (“%d”, &num1);
printf (“\n Please type a number: \n”);
scanf (“%d”, &num2);
printf (“\n Please type a number: \n”);
scanf (“%d”, &num3);
if ((num1 > num2) && (num1 >
num3))
printf (“num1 is the
biggest”); else
Exerci
#include se
<stdio.h> void
main ( )
{
/* read two
integers N1 and
N2, and
if one number is two times the other
number, for example, N1=10 and
N2=20,
print the sum of the two numbers
else print “condition not satisfied” */
}
Solutio
#include n
<stdio.h> void
main ( )
{
int num1,
num2;
printf (“\n Please type a number: \n”);
scanf (“%d”, &num1);
printf (“\n Please type a number: \n”);
scanf (“%d”, &num2);
if ((num1 == 2*num2) || (num2
== 2*num1))
printf (“result = %d”,
num1+num2); else
printf (“condition not
satisfied”);
N1 <= N3
#include <= N2
<stdio.h> void
main ( )
{
int N1, N3, N3;
wrong */
if (N1 <= N3
<= N2) <= N3) && (N2 >=
if ((N1 /* correct */
N3))
} /*
Precedence Order( 우선순
위)
1: ! (NOT),
unary
2: *, –% (algebraic operators)
3: /, (algebraic operators)
+,
–
4: <, <=, >, >= (comparison
operators)
5: ==,!= (comparison
operators)
6: && (Boolean AND)
Associativity
Order
Right to Left
!, unary –
Left to Right
everything
else
Example C
#include Program
<stdio.h> void
main ( )
{
int num1,
num2, num3;
printf (“\n Please type a number: \n”);
scanf (“%d”, &num1);
printf (“\n Please type a number: \n”);
scanf (“%d”, &num2);
printf (“\n Please type a number: \n”);
scanf (“%d”, &num3);
if (num3 + 3 <= -num2 + 3 *
num1)
printf (“compute result = TRUE”);
else
Example C
#include Program
<stdio.h> void
main ( )
{
int num1,
num2, num3;
printf (“\n Please type a number: \n”);
scanf (“%d”, &num1);
printf (“\n Please type a number: \n”);
scanf (“%d”, &num2);
printf (“\n Please type a number: \n”);
scanf (“%d”, &num3);
if (num3 + 3 <= (-num2 + 3) *
num1)
printf (“compute result = TRUE”);
else
Assignme
nt
Read chapter
3.1~3.9
Questio
n?