C Types
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
%d or %i int Try it »
%f or %F float 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() {
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
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.
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;
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;
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;
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;
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;
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
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 += 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
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
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;
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;
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;
}
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 ?