Introduction to Variables in C++
What is a Variable?
A variable is like a container in memory where you store some data. You give it a name and a type,
so the computer knows what kind of data you're storing.
Basic Types of Variables in C++
Type | What it stores | Example values | Size (approx.)
----------|----------------------------|---------------------|----------------
int | Integer numbers | -5, 0, 10, 1000 | 4 bytes
float | Decimal numbers (less precise) | 3.14, -1.5 | 4 bytes
double | Decimal numbers (more precise) | 3.14159, 2.718 | 8 bytes
char | A single character | 'a', 'Z', '9' | 1 byte
bool | True or False | true, false | 1 byte
short | Smaller integer | -32768 to 32767 | 2 bytes
long | Larger integer | Very large numbers | 4 or 8 bytes
string | A text | "Hello" | Varies
Example Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 20;
float height = 5.9;
double pi = 3.14159;
char grade = 'A';
bool isPassed = true;
short temp = -15;
long population = 7800000000;
string name = "Ali";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Height: " << height << endl;
cout << "Grade: " << grade << endl;
cout << "Passed? " << isPassed << endl;
cout << "Population: " << population << endl;
return 0;
Why Do We Use Variables in Programming?
Imagine you're baking a cake. You need to store ingredients like sugar, flour, and eggs. If you keep
everything in one bowl without labels, it gets confusing. Instead, you label each container. Variables
are like those labeled containers in your program.
Reasons to Use Variables:
1. Store and reuse values
2. Change values easily
3. Accept user input
4. Do calculations
5. Make your code readable
Think of variables as: "Named memory locations" that hold data you want to use or change.
Real-life analogy:
Real World | Programming Equivalent
------------------------|-------------------------
Calculator's memory | int result = 0;
Label on a box | Variable name
Value inside the box | Data stored in variable