Variables and Data Types
A variable is a named location used to store a value. C++ is strongly typed, so the variable’s data type determines what kind of value it can hold.
Common Data Types
| Type | Example | Use |
|---|---|---|
int | 25 | Whole numbers |
double | 88.5 | Decimal numbers |
char | 'A' | One character |
bool | true | True or false values |
string | "Alice" | Text |
Declaring and Initialising Variables
Variables example
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Alice";
int age = 20;
double score = 88.5;
char grade = 'A';
bool enrolled = true;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Score: " << score << endl;
cout << "Grade: " << grade << endl;
cout << boolalpha << "Enrolled: " << enrolled << endl;
return 0;
}Constants
Use const for a value that should not change while the program is running.
Constant example
const double TAX_RATE = 0.06;
double price = 100.0;
double tax = price * TAX_RATE;Practice task
Create variables for a product name, price, quantity, and availability. Display all four values.
Lesson Summary
Store text, whole numbers, decimal values, characters, and Boolean values.