📦 Lesson 3: Variables & Data Types
⏱️ Estimated time: 25 minutes | Difficulty: Beginner
Introduction
In C, you need to tell the computer exactly what kind of data you are storing. This is called a "type".
What Are Variables?
Variables are named containers that store data in your program. In C, you must declare the type of data a variable will hold before using it.
Declaring & Initializing Variables:
#include <stdio.h>
int main() {
// Declaration (creating a variable)
int age;
// Initialization (giving it a value)
age = 25;
// Declaration + Initialization (in one line)
int score = 95;
float height = 5.9;
char grade = 'A';
// Print them
printf("Age: %d\n", age);
printf("Score: %d\n", score);
printf("Height: %.1f\n", height);
printf("Grade: %c\n", grade);
return 0;
}
C Data Types
| Type | Size | Format | Example |
|---|---|---|---|
int |
4 bytes | %d |
42, -7, 0 |
float |
4 bytes | %f |
3.14, -0.5 |
double |
8 bytes | %lf |
3.14159265 |
char |
1 byte | %c |
'A', 'z', '9' |
short |
2 bytes | %hd |
Small integers |
long |
8 bytes | %ld |
Large integers |
Getting User Input with scanf
#include <stdio.h>
int main() {
int age;
char name[50]; // String (array of characters)
printf("Enter your name: ");
scanf("%s", name); // Read a string
printf("Enter your age: ");
scanf("%d", &age); // Read an integer (note the &)
printf("Hello %s! You are %d years old.\n", name, age);
return 0;
}
⚠️ Important: Notice the & before age in scanf? That's
the "address-of" operator. scanf needs the memory address to store the value. Strings (char arrays)
don't need it because the array name already IS an address!
Type Casting
int a = 10, b = 3;
printf("%d\n", a / b); // 3 (integer division!)
printf("%.2f\n", (float)a / b); // 3.33 (cast to float first)