π§ What is a Variable?
A variable in C++ is a named storage location that holds a value.
Think of it like a box with a label that stores information (like numbers or text) while your program runs.
π Syntax
dataType variableName = value;
π Example:
int age = 20;
-
int
β type of data (integer) -
age
β variable name -
20
β value assigned to the variable
πΉ Common Data Types in C++
Data Type | Description | Example |
---|---|---|
int |
Integer numbers | int a = 10; |
float |
Decimal numbers | float pi = 3.14; |
double |
Larger decimal numbers | double d = 5.678; |
char |
Single characters | char grade = 'A'; |
bool |
True or False | bool isOn = true; |
string |
Text (needs #include <string> ) |
string name = "Ali"; |
π― Example Code
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 18;
float height = 1.75;
char grade = 'A';
bool passed = true;
string name = "Ali";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Height: " << height << " m" << endl;
cout << "Grade: " << grade << endl;
cout << "Passed: " << passed << endl;
return 0;
}
π Rules for Naming Variables
β Allowed:
- Letters (
a-z
,A-Z
) - Digits (
0-9
) - Underscore
_
β Not Allowed:
- Starting with a number (e.g.,
2num
) - Special characters (
@
,#
,!
, etc.) - Reserved keywords (like
int
,return
,while
)
π Pro Tip
You can declare multiple variables of the same type on one line:
int x = 5, y = 10, z = 15;
β Summary
Concept | Example |
---|---|
Declare | int num; |
Initialize | num = 7; |
Combined | int num = 7; |
Output | cout << num; |
Top comments (0)