Data Types in C
In C programming, data types tell the compiler what kind of data a variable can store and how much memory should be allocated for it.
Choosing the correct data type is very important. It affects memory usage, performance, and correctness of your program.
Why Data Types Matter
Every value stored in a program occupies memory. Different data types occupy different amounts of memory.
For example:
- An integer needs less memory than a decimal number
- A character needs very small memory
- Choosing the wrong type may cause wrong results
Main Categories of Data Types in C
C data types are broadly divided into:
- Basic (Primitive) Data Types
- Derived Data Types
- User-Defined Data Types
In this lesson, we focus on Basic Data Types.
1. int (Integer Data Type)
The int data type is used to store whole numbers
without decimal values.
Examples of integers:
- 10
- -25
- 0
int age = 25;
int temperature = -10;
Here, age and temperature store integer values.
Typically, an int occupies 4 bytes of memory.
2. float (Decimal Numbers)
The float data type is used to store decimal (fractional) values.
Examples:
- 3.14
- 98.6
- -0.75
float pi = 3.14;
float temperature = 98.6;
Float values usually take 4 bytes of memory, but with limited precision.
3. double (More Precision)
The double data type stores decimal numbers
with higher precision than float.
double distance = 12345.6789;
A double typically occupies 8 bytes
and is preferred when accuracy is important.
4. char (Character Data Type)
The char data type stores a single character.
Characters are always written inside single quotes.
char grade = 'A';
char symbol = '@';
A char usually occupies 1 byte of memory.
Numerical Example
Let us combine multiple data types in one program.
#include <stdio.h>
int main() {
int age = 20;
float height = 5.8;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Grade: %c\n", grade);
return 0;
}
This program stores and prints integer, float, and character values.
Mini Practice
- Create variables for your age, weight, and first initial
- Use correct data types for each
- Print all values using
printf()
Quick Quiz
Q1. Which data type is used to store whole numbers?
The int data type is used to store whole numbers.
Q2. Which data type provides higher precision: float or double?
Double provides higher precision than float.
Q3. How many bytes does a char usually occupy?
A char usually occupies 1 byte of memory.
Q4. Which symbol is used for characters?
Single quotes (' ') are used for characters.
Q5. Why are data types important?
They control memory allocation, accuracy, and correctness of data.