0% found this document useful (0 votes)
2 views

Computer Programming Part 3

The document discusses data types and variables in C programming, detailing the various integer and floating-point types, their sizes, and ranges. It also covers variable declaration, initialization, naming conventions, and the use of constants. Additionally, it highlights the importance of choosing appropriate data types for memory efficiency and processing speed.

Uploaded by

gogizea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Computer Programming Part 3

The document discusses data types and variables in C programming, detailing the various integer and floating-point types, their sizes, and ranges. It also covers variable declaration, initialization, naming conventions, and the use of constants. Additionally, it highlights the importance of choosing appropriate data types for memory efficiency and processing speed.

Uploaded by

gogizea
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

3.

Data and Variables

1
Data is

level
exp
points
recharge
time

reset time

score of rank 1

level of rank 1

기초컴퓨터프로그래밍 2
Data type
Human data type/ computer
Computers process numbers (data). data type
There are specific types of numbers a computer can handle.

Data is stored in memory. Data type in C language

Data type in C Size (byte) Size refers to the


amount of memory
int (character) char 1 used to store/process
short 2 a given data type on
int 4 a computer.
integer
long 4
long long 8
real number float 4
(floating- double 8
point) long double 8 / 16
기초컴퓨터프로그래밍 3
Integer

Integer
– most commonly used data type

정수형의 범위

size in size in
data type range of representable numbers
byte bit
char 1 8 -128 ~ 127
short 2 16 -32,768 ~ 32,767
int 4 32 -2,147,483,648 ~ 2,147,483,647
long 4 32 -2,147,483,648 ~ 2,147,483,647
Approximately -9.22 quintillion to
long long 8 64
9.22 quintillion

기초컴퓨터프로그래밍 4
Integer

char type
– smallest number largest number
8 bit = 1 byte

0 0 0 0 0 0 0 0 =0 1 1 1 1 1 1 1 1 =255

0 to 255, total of 256 number


8
– With 1 byte (8 bits), 256 numbers (2^8) can be represented.
– negative numbers must also be represented, the range is from
-128 to 127, allowing 256 numbers to be expressed.
– representing negative numbers can be referenced in 'How
numbers are represented in computers.'
int type
32
– it can represent approximately 4.2 billion(2 ) numbers,
ranging from -2.1 billion기초컴퓨터프로그래밍
to +2.1 billion. 5
Integer

Choosing an Integer Type 컴퓨터의 자료형 중 선택하여 사용

– The data type must accommodate the required range.

– Prefer smaller data types when possible (to optimize memory


usage and speed).

int type
– Historically, the int type was 16 bits, but now it is 32 bits.

– In the future, it may become 64 bits or more.

char type
– used to store characters, so it is also referred to as a character
type.

기초컴퓨터프로그래밍 6
Quiz)

Answer
– What is the data type of the number 120?
– What data type is suitable for storing the number 120?
– What is the best data type to store/process 120 + 120?
– What is the difference between storing 120 as char and long
long?
– What data type is best for storing numbers between 0 and
500,000?
– What is the best data type to store a number between 0 and
300?
– Is char type an integer type or a character type?
– What is the most commonly used integer type?
– What is a 64-bit computer?
기초컴퓨터프로그래밍 7
Computers represent
Floating Point Types numbers using 0s
and 1s

Definition floating point


(↔ fixed point)
– Numbers that include a decimal point.
– Used for representing very large or very small values.

Significant
data type size (byte) range
digits
float 4 7 ±10-38 ~ 1038
double 8 15 ±10-308 ~ 10308
long double 8 15 ±10-308 ~ 10308

In Visual Studio, a long double is 8 bytes, while


in other compilers/systems, it is 12 or 16 bytes.

기초컴퓨터프로그래밍 8
floating point

Drawbacks of Floating Point Types


– Limited precision.

– Slower processing speed compared to integers.

– Prone to rounding errors.

significant digits
– Due to the limitations of the computer's storage method
(binary), digits beyond the reliable significant digits cannot be
trusted.

Why are there


significant digits?
Why do errors occur?"
기초컴퓨터프로그래밍 9
char

Definition
– Computers process numbers (integers and floating points).
– Characters are represented using numbers (e.g., ASCII codes).
– char type is used to store characters efficiently(int is not good?).
ASCII Code
– maps numbers from 0 to 127 to corresponding characters for
storing text
– ASCII Code is one method of interpreting numbers as characters.
– In any case, computers only store numbers
ASCII Code Examples
– Digits (0-9): 48 to 57
– Uppercase A, lowercase a: 65, 97 Korean char?
– Space, newline: 32, 10 Japanese char?
Chinese char?
기초컴퓨터프로그래밍 10
char

ASCII Code table

기초컴퓨터프로그래밍 11
unsigned

Unsigned Integer Types


data type range
unsigned char 0 ~ 255

unsigned short 0 ~ 65,535

unsigned int 0 ~ 4,294,967,295

unsigned long 0 ~ 4,294,967,295

unsigned long long 0 ~ 1800경

Useful when only non-negative values are needed.

Data types that are not provided by default (e.g., complex numbers)
must be created and used by the developer.

기초컴퓨터프로그래밍 12
Quiz)

Answer the following questions with O (True) or X


(False), or provide an explanation:
– A computer can store numbers with an infinite number of
decimal places.
– When using real number, “float” type is typically used.
– Floating-point types are used more frequently than integer
types.
– The size of floating-point types is already determined.
– Floating-point types are fast when calculated by the CPU.
– The number of significant digits in floating-point numbers can
vary.
– Computers have a separate data type for processing
characters.
– For storing zero or positive integers, you must use unsigned.

기초컴퓨터프로그래밍 13
Data type in C
char

char
int / short
int / short

char char

char int

기초컴퓨터프로그래밍 14
C 언어 자료형의 이해

무조건 큰 범위의 자료형을 선택한다면?


– 모든 정수는 long long ?
자료형의 선택은 개발자의 몫
– 모든 실수는 long double ?

메모리는 소중하다.
– 정수(int) 1개를 저장할 때에는 4 바이트를 차지하지만,

– 정수(int) 10억 개를 저장할 때에는 4GB를 차지한다.

짧은 단위일수록 처리 속도가 빠르다.


– char 형 덧셈이 long long형 덧셈보다 훨씬 빠르다.

– 정수형 연산이 실수형 연산보다 훨씬 빠르다.

기초컴퓨터프로그래밍 15
Variables
A variable is used to
store values and perform
Definition calculations.
– A space in memory used to store and manipulate data in a
program.
– In C programs, variables are used by assigning them names.
– Once a value is stored in a variable, it can be retrieved at any time.
– New values can be stored in a variable at any time.
– A variable must have a data type.
– A variable stores values that match its data type.
– A variable must be declared before it is used.
• data type varname
폰노이만 구조 모든 프로그램은 메모리에 탑재되어 실행된다.
메모리

변수 프로그램
기초컴퓨터프로그래밍 16
Variable Declaration

data type varname;


data type var1, var2, …;

Declare a variable with a specific data type and name


as needed.
– Once declared, it is created when the program runs.
example
주 메모리
– int number; number value score total

– int value, score, total;

Where should a variable be declared


– Declare a variable before using it (storing a value).
– place it after the line 'int main( ) {'.
기초컴퓨터프로그래밍 17
Assigning Values to Variables

variable = value ; = means


assigning

To assign a value to a variable, use the '=' operator.


– The value on the right is assigned to the variable on the left.

int score, number, value ;


main memory
score = 90;
90
number value score

기초컴퓨터프로그래밍 18
example
#include <stdio.h>
int main( )
{
int total, score, value;
total = 100;
score = 90;
value = 10; // 10.1 이라면?

/* 이제 무엇인가 합시다. */
score = total + value;
printf("%d\n", score);
}

기초컴퓨터프로그래밍 19
variable name

Variable Naming Rules


– Can contain letters, numbers, and underscores (_).
– Must start with a letter or _.
– Case-sensitive.
Korean variable names are also allowed.
– Supported in C99 (can be in any language).
– It is not commonly used among existing developers, so it is
recommended to avoid it if possible.
example
– appropriate example (number, _number7, My_address)
– inappropriate example (7even, num@#, score-score)

기초컴퓨터프로그래밍 20
variable name

good variable name


– The variable name should give a clear idea of what the
variable stores.

– It is even better if the data type of the variable is known.


• IDE tools can provide information about the variable's data type.

– It is fine to use more than one word.


• totalNum, myAddress 등

bad variable name


– a, b, c, a1, a2, aaaa, bbbb, kkk

기초컴퓨터프로그래밍 21
variable name
https://www.newiki.net/wiki/코딩_스타일
Naming variables with multiple words
– Capitalizing the first letter of each word : AverageScore,
TotalScore
– Adding an underscore between words. : average_score,
total_score
Attaching a data type to a variable
– iTotalScore : variable name clearly indicates that it is an integer
– fAverageScore : floating type
Invalid variable name (keyword, or reserved word)
– Reserved words in C language for special purposes
• auto, break, case, char, const, continue, default, do, double
• else, enum, extern, float, for, goto, if, return, short, sighed,
• sizeof, static, struct, switch, typedef, union, unsigned, void, while 22
기초컴퓨터프로그래밍
Variable initialization

int value;
int value = 10;
value = 10;

Declare a variable and assign a value at the same time.


– Initialization is the process of assigning the initial value.
Examples of declaring and initializing multiple
variables.
– int number = 20, value = 30, score = 50;

If a variable is declared but not initialized, it contains


garbage values.
It is not necessary to initialize all variables.

기초컴퓨터프로그래밍 23
Variable initialization

#include <stdio.h>

garbage values.
int main( )
{ main memory
int number = 10, value; 10 -873213
number value

The space for the variable has been created.


Before assigning a value, it contains garbage values.

value = number + 10; Since the value will be assigned later,


it was not initialized separately.
}

기초컴퓨터프로그래밍 24
Variable initialization

You must initialize the variable with a value that


matches its data type.
– Otherwise,

int num;

float cel;

num = 3.14;

cel = 3.0;

cel = 4;

Even if an incorrect value is assigned, no error will occur


(a warning will be given).

기초컴퓨터프로그래밍 25
Variable initialization

The following is correct usage.


int value, name ; // the 'value' variable does not
// need to be initialized.

name = 50;
value = name; // Before using the garbage value
// in the 'value' variable,
//it is filled with another value.

warning or error
int value, name;
value = name;

– The 'name' variable is not initialized, so it contains garbage


values, but it is being assigned to 'value'.
기초컴퓨터프로그래밍 26
error and warning

The compiler points out issues as errors or warnings


when compiling the program.
error
– An incorrect syntax for C language was used. Compilation is
not possible.
– Execution is not possible until the issue is resolved.
warning
– The syntax is correct according to C language, but it appears
to be a mistake by the developer. Compilation is possible, but
there may be potential issues. It serves as a warning to the
developer.

– The results should be carefully checked.


기초컴퓨터프로그래밍 27
Exercise

Write the following program.


– Declare variables for Korean, English, and Math scores.

– Store appropriate scores in these variables.

– Declare a total variable and store the sum of scores.

– Print the scores and total using printf.

printf(“%d\n”, total);
// Display the value of the total variable on the screen.

기초컴퓨터프로그래밍 28
sizeof operator

Operator that tells the size of a data type


int score;

score = 99;

printf( "%d\n", sizeof (int)); // print the size of int


printf( "%d\n", sizeof score); // print the size of
// score variable

The size of a data type may vary across different systems.


– In this case, it is recommended to check using the sizeof
operator.
not need for it right now

기초컴퓨터프로그래밍 29
constant

value in a program
example
– integer constant 10, 384

– float constant 5.321, 3.141592

– char constant ‘A’

score = 10;

In a computer that stores

grade = 'B'; only numbers, what value


does 'B' store?"
fvalue = 3.1415926;
기초컴퓨터프로그래밍 30
named constant

Like a variable, a value is assigned to an identifier.


– Fixed values that do not change

const int MAX_SCORE = 100 ;



score = MAX_SCORE;
MAX_SCORE = 200; // error

Reasons for using named constants:


– Improve program readability

– Prevent accidental value changes


recommendation,
Preferred constant naming: not an obligation

– Use uppercase letters to indicate that it is a constant, unlike a


기초컴퓨터프로그래밍 31
variable.
number notation (integer)

Number systems available in C programming


– 2, 8, 10, 16진수 decimal and hexadecimal
Relationship between number systems are mainly used
binary, octal, and hexadecimal: Binary numbers are available
– Grouping 3 binary digits gives octal. starting from C11.
– Grouping 4 binary digits gives hexadecimal.

110010100110 2진수 0100110010100110 2진수

6 2 4 6 4 C A 6 16진수
8진수

기초컴퓨터프로그래밍 32
number notation (integer)

Representation of number systems in C programs


– Octal: Prefix the constant with 0 (zero).

– Hexadecimal: Prefix the constant with 0x.

– Binary: Prefix the constant with 0b

– example:
value = 010; // 8진수 10, 10진수 8을 value에 넣는다.
score = 0x10; // 16진수 10, 10진수 16을 score에 넣는다.

기초컴퓨터프로그래밍 33
Input of exponential data(float)

Limitations of input:
– You cannot input 10100 (big number) in the following way (error).

double fvalue =
10000000000000000000000000000000000000000…………

Input in exponential form


– fvalue = 1.0e100; // 1.0 * 10

기초컴퓨터프로그래밍 34
Exercise

다음의 프로그램을 작성하라.


– The value of pi (π) is 3.1415926536

– The area of a circle is πr 2

– Assign a value to the variable 'radius' and store the area of


the circle with radius 'radius' in the 'area' variable.

– Print the result on the screen.

– use the following sentence for output


• printf(“%f\n”, area);

기초컴퓨터프로그래밍 35
Overflow & Underflow
Data type in C size (byte) range
char 1 -128~127
short 2 -32768 - 32767
integer int 4 -2,147,483,648 ~ 2,147,483,647
long 4 -2,147,483,648 ~ 2,147,483,647
long long 8 약 -922경 ~ 922경 (이하 자리 생략)

Occurs when a number exceeds the storage limit of a data


type.
– char values exceeding 127 wrap around to negative numbers.
Overflow & Underflow Why doesn't it notify us?

– It is not flagged as an error, but unexpected values may be present.


– It is desirable to prevent this from occurring.
기초컴퓨터프로그래밍 36
Number and Suffix

float a, b;

a = 0.1; // warning
b = 0.5; // OK

Floating-point constants are also categorized into float


and double types.
If a double constant is assigned to a float variable, a
warning will appear due to potential data loss.
Suffixes are used when defining constants as specific
data types.
– a = 0.1F ; // Treat 0.1 as a float.
Types of suffixes
– U, L, UL, LL, ULL(integer suffix), F, L (float suffix)
기초컴퓨터프로그래밍 37
Integer

Negative integers(2's complement) positive integer


-2,147,483,648 1000……0000 2,147,483,647 0111……1111

-2,147,483,647 1000……0001 2,147,483,646 0111……1110

… … … …

-3 1111……1101 3 0000……0011

-2 1111……1110 2 0000……0010

-1 1111……1111 1 0000……0001

0 0000……0000 0 0000……0000

Let's find the reasons for overflow/underflow in this table.

기초컴퓨터프로그래밍 38
float notation

± 𝟏. 𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇𝒇 ∗ 𝟐𝒆𝒆𝒆𝒆𝒆𝒆𝒆𝒆−𝟏𝟐𝟕
exponent
mentissa

0 e e e e e e e e f f f f f f f f f f f f f f f f f f f f f f f

1 bit 8 bit 23 bit

long double type varies across different systems.


기초컴퓨터프로그래밍 39
exercise

Verify the following result with a program


– 256 * 256 * 256 * 256

– Assign 0.1 to a variable, then print it on the screen. use the


following sentence for output.
• printf(“%.20f\n”, var );

• This sentence means to display up to 20 decimal places.


15 -10
– Print the result of 10 * 10

기초컴퓨터프로그래밍 40

You might also like