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

C Types

The document provides a comprehensive overview of C data types, including basic data types like int, float, double, and char, along with their sizes and format specifiers. It also covers type conversion, constants, operators, and examples of using these concepts in programming. Additionally, it discusses the importance of understanding data types for memory usage and performance in C programming.

Uploaded by

Lê Hồng Minh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C Types

The document provides a comprehensive overview of C data types, including basic data types like int, float, double, and char, along with their sizes and format specifiers. It also covers type conversion, constants, operators, and examples of using these concepts in programming. Additionally, it discusses the importance of understanding data types for memory usage and performance in C programming.

Uploaded by

Lê Hồng Minh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

C Types

Contents
Basic Data Types.......................................................................................................................2
Basic Format Specifiers.............................................................................................................3
The char Type............................................................................................................................4
ASCII......................................................................................................................................4
Notes on Characters..............................................................................................................4
Numeric Types...........................................................................................................................5
C Decimal Precision...............................................................................................................5
C The sizeof Operator................................................................................................................6
C Data Types Examples.........................................................................................................6
C Type Conversion....................................................................................................................7
Implicit Conversion.................................................................................................................7
Explicit Conversion.................................................................................................................8
itoa and atoi............................................................................................................................8
C Constants...............................................................................................................................9
Notes On Constants...............................................................................................................9
C Operators................................................................................................................................9
Arithmetic Operators................................................................................................................10
Assignment Operators.............................................................................................................10
Comparison Operators.............................................................................................................11
Logical Operators.....................................................................................................................12
C Booleans...............................................................................................................................12
Boolean Variables................................................................................................................12
Comparing Values and Variables.........................................................................................13
C ctype Functions....................................................................................................................14
Applications..............................................................................................................................14
Collatz Problem (3n+1).........................................................................................................14
Constance in <limits.h> and <float.h>......................................................................................16

Basic Data Types


The data type specifies the size and type of information the variable will store.
In this tutorial, we will focus on the most basic ones:
Data Size Description Example
Type
int 2 or 4 Stores whole numbers, without decimals 1
bytes

float 4 bytes Stores fractional numbers, containing one or 1.99


more decimals. Sufficient for storing 6-7
decimal digits

double 8 bytes Stores fractional numbers, containing one or 1.99


more decimals. Sufficient for storing 15 decimal
digits

char 1 byte Stores a single character/letter/number, or 'A'


ASCII values

Basic Format Specifiers


There are different format specifiers for each data type. Here are some of them:
Format Data Type Try it
Specifier

%d or %i int Try it »

%f or %F float Try it »

%lf double Try it »

%c char Try it »

%s Used for strings (text), which you will learn more Try it »
about in a later chapter
Note: It is important that you use the correct format specifier for the specified data type, or the
program may produce errors or even crash.
Lật số nguyên Rev(x)
#include <stdio.h>
/* lay phai ghep phai
chuyen chu so don vi cua x sang y */
int Rev(int x) {
int y = 0;
// lay dau
int sign = (x < 0) ? -1 : 1;
if (x < 0) {
x = abs(x);
}
while(x) {
y = y*10 + (x % 10);
x /= 10;
}
return sign*y;
}
int main() {

printf("\n %d", Rev(-2000));


return 0;
}

The char Type


The char data type is used to store a single character.
The character must be surrounded by single quotes, like 'A' or 'c', and we use the %c format
specifier to print it:
Example
char myGrade = 'A';
printf("%c", myGrade);
Alternatively, if you are familiar with ASCII, you can use ASCII values to display certain
characters. Note that these values are not surrounded by quotes (''), as they are numbers:
Example
char a = 65, b = 66, c = 67;
printf("%c", a);
printf("%c", b);
printf("%c", c);
Tip: A list of all ASCII values can be found in our ASCII Table Reference.

ASCII

#include <stdio.h>

void Go() {
printf(" ? ");
char c;
scanf("%c", &c);
if (c == 10) return; // ENTER
if (c == '.') exit(0);
}

void ASCII() {
int i;
for (i = 0; i < 128; i++) {
printf("\n %c %d", i, i); Go();
}
}

int main() {
ASCII();
return 0;
}

Notes on Characters
If you try to store more than a single character, it will only print the last character:
Example
char myText = 'Hello';
printf("%c", myText);
Note: Don't use the char type for storing multiple characters, as it may produce errors.
To store multiple characters (or whole words), use strings (which you will learn more about in a
later chapter):
Example
char myText[] = "Hello";
printf("%s", myText);

Numeric Types
Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.
int
int myNum = 1000;
printf("%d", myNum);
float
float myNum = 5.75;
printf("%f", myNum);
double
double myNum = 19.99;
printf("%lf", myNum);
float vs. double
The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is six or seven decimal digits, while double variables have a
precision of about 15 digits. Therefore, it is often safer to use double for most calculations - but
note that it takes up twice as much memory as float (8 bytes vs. 4 bytes).
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;

printf("%f\n", f1);
printf("%lf", d1);

C Decimal Precision

Set Decimal Precision


You have probably already noticed that if you print a floating point number, the output will show
many digits after the decimal point:
Example
float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%f\n", myFloatNum); // Outputs 3.500000


printf("%lf", myDoubleNum); // Outputs 19.990000
If you want to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a
number that specifies how many digits that should be shown after the decimal point:
Example
float myFloatNum = 3.5;
printf("%f\n", myFloatNum); // Default will show 6 digits after the
decimal
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits

C The sizeof Operator

Get the Memory Size


We introduced in the data types chapter that the memory size of a variable varies depending on
the type:
Data Type Size

int 2 or 4 bytes

float 4 bytes

double 8 bytes

char 1 byte
The memory size refers to how much space a type occupies in the computer's memory.
To actually get the size (in bytes) of a data type or variable, use the sizeof operator:
Example
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(float));
printf("%d\n", sizeof(double));
printf("%d\n", sizeof(char));
Note that we use the %lu format specifer to print the result, instead of %d. It is because the
compiler expects the sizeof operator to return a long unsigned int (%lu), instead of int (%d). On
some computers it might work with %d, but it is safer to use %lu.
Why Should I Know the Size of Data Types?
Knowing the size of different data types is important because it says something about memory
usage and performance.
For example, the size of a char type is 1 byte. Which means if you have an array of
1000 char values, it will occupy 1000 bytes (1 KB) of memory.
Using the right data type for the right purpose will save memory and improve the
performance of your program.
You will learn more about the sizeof operator later in this tutorial, and how to use it in different
scenarios.

C Data Types Examples

Real-Life Example
Here's a real-life example of using different data types, to calculate and output the total cost of a
number of items:
Example
// Create variables of different data types
int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';
// Print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);

C Type Conversion
Type Conversion
Sometimes, you have to convert the value of one data type to another type. This is known
as type conversion.
For example, if you try to divide two integers, 5 by 2, you would expect the result to be 2.5. But
since we are working with integers (and not floating-point values), the following example will just
output 2:
Example
int x = 5;
int y = 2;
int sum = 5 / 2;

printf("%d", sum); // Outputs 2

To get the right result, you need to know how type conversion works.
There are two types of conversion in C:
 Implicit Conversion (automatically)
 Explicit Conversion (manually)

Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a value of one type to
another.
For example, if you assign an int value to a float type:
Example
// Automatic conversion: int to float
float myFloat = 9;

printf("%f", myFloat); // 9.000000

As you can see, the compiler automatically converts the int value 9 to a float value of 9.000000.
This can be risky, as you might lose control over specific values in certain situations.
Especially if it was the other way around - the following example automatically converts the float
value 9.99 to an int value of 9:
Example
// Automatic conversion: float to int
int myInt = 9.99;

printf("%d", myInt); // 9

What happened to .99? We might want that data in our program! So be careful. It is important
that you know how the compiler work in these situations, to avoid unexpected results.
As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5. And as you
know from the beginning of this page, if you store the sum as an integer, the result will only
display the number 2. Therefore, it would be better to store the sum as a float or a double, right?
Example
float sum = 5 / 2;

printf("%f", sum); // 2.000000

Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the
division. In this case, you need to manually convert the integer values to floating-point values.
(see below).

Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the value.
Considering our problem from the example above, we can now get the right result:
Example
// Manual conversion: int to float
float sum = (float) 5 / 2;

printf("%f", sum); // 2.500000

You can also place the type in front of a variable:


Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%f", sum); // 2.500000


And since you learned about "decimal precision" in the previous chapter, you could make the
output even cleaner by removing the extra zeros (if you like):
Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%.1f", sum); // 2.5

itoa and atoi


char s[30];
itoa(19,s,16);
printf("\n %s", s);

Real-Life Example
Here's a real-life example of data types and type conversion where we create a program to
calculate the percentage of a user's score in relation to the maximum score in a game:
Example
// Set the maximum possible score in the game to 500
int maxScore = 500;

// The actual score of the user


int userScore = 423;

/* Calculate the percantage of the user's score in relation to the maximum


available score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0;

// Print the percentage


printf("User's percentage is %.2f", percentage);

C Constants

Constants
If you don't want others (or yourself) to change existing variable values, you can use
the const keyword.
This will declare the variable as "constant", which means unchangeable and read-only:
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are unlikely to
change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;

Notes On Constants
When you declare a constant variable, it must be assigned with a value:
Example
Like this:
const int minutesPerHour = 60;
This however, will not work:
const int minutesPerHour;
minutesPerHour = 60; // error

Good Practice
Another thing about constant variables, is that it is considered good practice to declare them
with uppercase.
It is not required, but useful for code readability and common for C programmers:
Example
const int BIRTHYEAR = 1980;

C Operators
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int myNum = 100 + 50;

Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
C divides the operators into the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example Try it

+ Addition Adds together two values x+y Try it »

- Subtraction Subtracts one value from x-y Try it »


another

* Multiplication Multiplies two values x*y Try it »

/ Division Divides one value by x/y Try it »


another

% Modulus Returns the division x%y Try it »


remainder

++ Increment Increases the value of a ++x Try it »


variable by 1

-- Decrement Decreases the value of a --x Try it »


variable by 1

Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
Example
int x = 10;
The addition assignment operator (+=) adds a value to a variable:
Example
int x = 10;
x += 5;
A list of all assignment operators:
Operator Example Same As Try it

= x=5 x=5 Try it »

+= x += 3 x=x+3 Try it »

-= x -= 3 x=x-3 Try it »

*= x *= 3 x=x*3 Try it »

/= x /= 3 x=x/3 Try it »

%= x %= 3 x=x%3 Try it »

&= x &= 3 x=x&3 Try it »

|= x |= 3 x=x|3 Try it »

^= x ^= 3 x=x^3 Try it »

>>= x >>= 3 x = x >> 3 Try it »

<<= x <<= 3 x = x << 3 Try it »

Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or false (0). These
values are known as Boolean values, and you will learn more about them in
the Booleans and If..Else chapter.
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
A list of all comparison operators:
Operator Name Example Description Try it

== Equal to x == y Returns 1 if the values are Try it


equal »

!= Not equal x != y Returns 1 if the values are not Try it


equal »
> Greater than x>y Returns 1 if the first value is Try it
greater than the second value »

< Less than x<y Returns 1 if the first value is Try it


less than the second value »

>= Greater than x >= y Returns 1 if the first value is Try it


or equal to greater than, or equal to, the »
second value

<= Less than or x <= y Returns 1 if the first value is Try it


equal to less than, or equal to, the »
second value

Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values, by combining
multiple conditions:
Operator Name Example Description Try it

&& AND x < 5 && x < Returns 1 if both statements Try it »


10 are true

|| OR x < 5 || x < 4 Returns 1 if one of the Try it »


statements is true

! NOT !(x < 5 && x < Reverse the result, returns 0


10) if the result is 1

C Booleans
Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:
 YES / NO
 ON / OFF
 TRUE / FALSE
For this, C has a bool data type, which is known as booleans.
Booleans represent values that are either true or false.

Boolean Variables
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must import the following header file to use it:
#include <stdbool.h>
A boolean variable is declared with the bool keyword and can take the values true or false:
bool isProgrammingFun = true;
bool isFishTasty = false;
Before trying to print the boolean variables, you should know that boolean values are returned
as integers:
 1 (or any other number that is not 0) represents true
 0 represents false
Therefore, you must use the %d format specifier to print a boolean value:
Example
// Create boolean variables
bool isProgrammingFun = true;
bool isFishTasty = false;

// Return boolean values


printf("%d", isProgrammingFun); // Returns 1 (true)
printf("%d", isFishTasty); // Returns 0 (false)
However, it is more common to return a boolean value by comparing values and variables.

Comparing Values and Variables


Comparing values are useful in programming, because it helps us to find answers and make
decisions.
For example, you can use a comparison operator, such as the greater than (>) operator, to
compare two values:
Example
printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater than 9

From the example above, you can see that the return value is a boolean value (1).
You can also compare two variables:
Example
int x = 10;
int y = 9;
printf("%d", x > y);

In the example below, we use the equal to (==) operator to compare different values:
Example
printf("%d", 10 == 10); // Returns 1 (true), because 10 is equal to 10
printf("%d", 10 == 15); // Returns 0 (false), because 10 is not equal to
15
printf("%d", 5 == 55); // Returns 0 (false) because 5 is not equal to 55

You are not limited to only compare numbers. You can also compare boolean variables, or even
special structures, like arrays (which you will learn more about in a later chapter):
Example
bool isHamburgerTasty = true;
bool isPizzaTasty = true;

// Find out if both hamburger and pizza is tasty


printf("%d", isHamburgerTasty == isPizzaTasty);
C If ... Else
C ctype Functions
The <ctype.h> header provides many functions for classifying and modifying characters.
Function Description

isalnum() Checks whether a character is alphanumeric

isalpha() Checks whether a character is a letter

isblank() Checks whether a character is a space or tab

iscntrl() Checks whether a character is a control character

isdigit() Checks whether a character is a decimal digit

isgraph() Checks whether a character has a graphical representation

islower() Checks whether a character is a lowercase letter

isprint() Checks whether a character is a printable character

ispunct() Checks whether a character is a punctuation character

isspace() Checks whether a character is a whitespace character

isupper() Checks whether a character is an uppercase letter

isxdigit() Checks whether a character is a hexadecimal digit

tolower() Returns a lowercase version of a character

toupper() Returns an uppercase version of a character

Applications
Collatz Problem (3n+1)
Cho số tự nhiên n. Tạo dãy số
 n lẻ thay bằng 3n+1
 Nếu n chẵn thay bằng n/2
Nếu n = 1: stop
a) Sinh Dãy Collatz(n)
b) Tính chiều dài của dãy Collatz(n)
c) Biết chiều dài m. Tìm n đầu tiên để Len(n) = m.
Algorithm

Program

/*
Name: Collatz problem
Copyright: (C) 2024
Author: DevC Fan
Date: 06-10-24 13:56
Description:
a) Collatz(n)
b) Len(n)
c) Len(n) = m, n = ?
*/

//#include <stdio.h>
//#include <string.h>
#define Odd(n) (n) % 2 == 1
#define Even(n) !(Odd(n))
#define MN 1000000

int a[MN];

void Go() {
printf(" ? ");
int c = getchar();
if (c == 10) return; // ENTER
if (c == '.') exit(0);
}

int Collatz(int n) {
int c = 0; // counter
a[c] = n;
while (n > 1) {
n = (Odd(n)) ? 3*n + 1 : n/2;
a[++c] = n;
}
return c+1;
}

// a
int Len(int n) {
int c = 1; // counter
while (n > 1) {
++c;
if (Odd(n)) {
n = (3*n + 1) / 2;
++c;
} else n /= 2;
}
return c;
}

void Printa(int m) {
int i;
for(i = 0; i < m; ++i)
printf(" %d", a[i]);
}

main() {
int i;
for(i = 1; i < 100; ++i) {
printf("\n Len(%d) = %d : ", i, Len(i));
Printa(Collatz(i));
Go();
}
printf("\n T h e E n d");
return 0;
}

Constance in <limits.h> and <float.h>


The header <limits.h> defines constants for the sizes of integral types. The
values below are acceptable minimum magnitudes; larger values may be used.

CHAR_BIT 8 bits in a char


CHAR_MAX UCHAR_MAX or SCHAR_MAX maximum value of char
CHAR_MIN 0 or SCHAR_MIN maximum value of char
INT_MAX 32767 maximum value of int
INT_MIN -32767 minimum value of int
LONG_MAX 2147483647 maximum value of long
LONG_MIN -2147483647 minimum value of long
SCHAR_MAX +127 maximum value of signed char
SCHAR_MIN -127 minimum value of signed char
SHRT_MAX +32767 maximum value of short
SHRT_MIN -32767 minimum value of short
UCHAR_MAX 255 maximum value of unsigned char
UINT_MAX 65535 maximum value of unsigned int
ULONG_MAX 4294967295 maximum value of unsigned long
USHRT_MAX 65535 maximum value of unsigned short
The names in the table below, a subset of <float.h>, are constants related to
floating-point arithmetic. When a value is given, it represents the minimum
magnitude for the corresponding quantity. Each implementation defines
appropriate values.
FLT_RADIX 2 radix of exponent, representation, e.g., 2, 16
FLT_ROUNDS floating-point rounding mode for addition
FLT_DIG 6 decimal digits of precision
FLT_EPSILON 1E-5 smallest number x such that 1.0+x != 1.0
FLT_MANT_DIG number of base FLT_RADIX in mantissa
FLT_MAX 1E+37 maximum floating-point number

FLT_MAX_EXP maximum n such that FLT_RADIXn-1 is representable


FLT_MIN 1E-37 minimum normalized floating-point number

FLT_MIN_EXP minimum n such that 10n is a normalized number

DBL_DIG 10 decimal digits of precision


DBL_EPSILON 1E-9 smallest number x such that 1.0+x != 1.0
DBL_MANT_DIG number of base FLT_RADIX in mantissa
DBL_MAX 1E+37 maximum double floating-point number
DBL_MAX_EXP maximum n such that FLT_RADIXn-1 is representable
DBL_MIN 1E-37 minimum normalized double floating-point number
DBL_MIN_EXP minimum n such that 10n is a normalized number

Trong ngôn ngữ lập trình C các kiểu dữ liệu số cơ sở bao gồm: int, long, short, char, float,
double. Mỗi kiểu số có những đặc trưng sau đây:
 size: là số byte biểu diễn số đó. Mỗi byte chiếm 8 bít, mỗi bít có giá trị 0 hoặc 1.
 Giá trị nhỏ nhất (MIN) và giá trị lớn nhất (MAX). Nếu bạn phát sinh ra các số nằm
ngoài khoảng MIN..MAX thì sẽ gây ra hiện tượng tràn số. Thông thường C++ không
báo lỗi tràn số, do đó, hiện tượng này có thể dẫn đến sai lệch kết quả.
Program dưới đây sẽ hiển thị kích thước và các giá trị MIN..MAX của mỗi kiểu số trong C+
+.
Program
/*
Name: Numbers
Copyright:
Author:
Date: 03-10-24 09:42
Description:
int, short. long, float, double
*/

#include <stdio.h>
#include <stdlib.h>
#include <float.h>
//#include <string.h>
//#include <ctype.h>
//#include <float.h>

void Go() {
printf(" ? ");
char c = getchar();
if (c == 10) return; // ENTER
if (c == '.') exit(0);
}

void Data() {
printf("\n size of int %d bytes, ", sizeof(int));
printf(" min max: %d %d", INT_MIN, INT_MAX);
printf("\n size of long %d bytes, ", sizeof(long));
printf(" min max: %d %d", LONG_MIN, LONG_MAX);
printf("\n size of short %d bytes, ", sizeof(short));
printf(" min max: %d %d", SHRT_MIN, SHRT_MAX);
printf("\n size of char %d bytes, ", sizeof(char));
printf(" min max: %d %d", CHAR_MIN, CHAR_MAX);
Go();
printf("\n size of float %d bytes, ", sizeof(float));
printf(" min max: %f %f", FLT_MIN, FLT_MAX);
printf("\n size of double %d bytes", sizeof(double));
printf("\n min max: %.10e, %.10e", DBL_MIN, DBL_MAX);
}

main() {
Data();
printf("\n T h e E n d");
return 0;
}
Output
size of int 4 bytes, min max: -2147483648 2147483647
size of long 4 bytes, min max: -2147483648 2147483647
size of short 2 bytes, min max: -32768 32767
size of char 1 bytes, min max: -128 127 ?

size of float 4 bytes, min max: 0.000000


340282346638528860000000000000000000000.000000
size of double 8 bytes
min max: 2.2250738585e-308, 1.7976931349e+308
T h e E n d
--------------------------------
Process exited after 1.684 seconds with return value 0
Press any key to continue . . .

You might also like