Where does a program keep the numbers and words it works with, and how does it know what it may do with them? The answer is the variable, together with the rule that every variable has a type.
Variables: named places in memory
A variable is a named place in memory that holds a value. You declare it by writing a type and a name, and you can initialise it, which means giving it a first value, in the same line. The = sign means assignment: store the value on the right into the variable on the left. So age = age + 1 is not a false equation. It says: take the current value of age, add one, and store the result back in age.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Asha";
int age = 19;
double height = 1.72; // metres
char grade = 'A';
bool passed = true;
cout << name << ": age " << age << ", height " << height << " m" << endl;
cout << "Grade " << grade << ", passed = " << passed << endl;
age = age + 1; // assignment changes the stored value
cout << "Next year: " << age << endl;
return 0;
}
Asha: age 19, height 1.72 m
Grade A, passed = 1
Next year: 20
Choose names that say what a variable holds, such as totalMarks rather than x. A name can use letters, digits and underscores, cannot start with a digit, and cannot be a keyword such as int or return. Names are case-sensitive, so age and Age are different variables. If a value must never change, declare it const, as in const double PI = 3.14159;. Changing it later is a compile error.
Uninitialised variables
Writing int total; with no value leaves whatever junk was already in that memory. Reading it is undefined behaviour: the program may print garbage, or work today and fail tomorrow. Always give a variable a starting value, such as int total = 0;.
The basic types
The type decides what a variable can hold and how much memory it takes. These are the ones you will use most:
| Type | Typical size | Holds | Example |
|---|---|---|---|
int | 4 bytes | whole numbers, about -2.1 billion to 2.1 billion | 19, -7 |
long long | 8 bytes | much larger whole numbers, up to about 9.2 × 1018 | 5000000000 |
double | 8 bytes | decimal numbers, about 15 digits of accuracy | 1.72 |
float | 4 bytes | decimal numbers, about 6 to 7 digits of accuracy | 1.72f |
char | 1 byte | one character, in single quotes | 'A' |
bool | 1 byte | true or false | true |
string | varies | text, in double quotes | "Asha" |
The sizes are typical for today’s computers. The standard guarantees only minimum sizes, and that a char is exactly one byte. The sizeof operator reports the real size on your machine.
An int tops out at 2,147,483,647, which is over 214 crore. A signed integer that goes past its limit overflows, and the C++ standard does not say what happens next, so the result cannot be trusted. For example, 12! = 479,001,600 fits in an int, but 13! = 6,227,020,800 does not. Use long long when numbers can grow large.
A char really stores a number, the character’s code. In ASCII, ‘A’ is 65, ‘B’ is 66 and ‘a’ is 97. That is why 'A' + 1 is the number 66, while char('A' + 1) is ‘B’.
Check your computer
Write a program that prints sizeof(char), sizeof(int), sizeof(long long) and sizeof(double). On most computers you will see 1, 4, 8 and 8.
Arithmetic and the integer-division trap
The arithmetic operators are +, -, *, / and % (remainder).
#include <iostream>
using namespace std;
int main() {
int a = 17, b = 5;
cout << "a + b = " << a + b << endl;
cout << "a - b = " << a - b << endl;
cout << "a * b = " << a * b << endl;
cout << "a / b = " << a / b << endl; // integer division
cout << "a % b = " << a % b << endl; // remainder
cout << "a / 5.0 = " << a / 5.0 << endl; // one operand is double
return 0;
}
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
a / 5.0 = 3.4
When both operands are integers, / gives an integer: the decimal part is thrown away, and for negative numbers the result is cut toward zero, so -7 / 2 is -3. The % operator gives the remainder and works only on integers. If either operand is a double, you get ordinary division, as in a / 5.0.
The integer-division trap
To convert Celsius to Fahrenheit we use F = C × 9/5 + 32. In C++, celsius * (9 / 5) + 32 with celsius = 37 gives 69, not 98.6, because 9 / 5 is integer division and equals 1. Write celsius * 9.0 / 5 + 32 and you get 98.6.
Operators have precedence: *, / and % are done before + and -, so 2 + 3 * 4 is 14. Brackets come first, so (2 + 3) * 4 is 20. When in doubt, add brackets. Updating a variable is so common that C++ has shortcuts:
| Statement | Same as | If x starts at 10, x becomes |
|---|---|---|
x += 5 | x = x + 5 | 15 |
x -= 4 | x = x - 4 | 6 |
x *= 3 | x = x * 3 | 30 |
x /= 4 | x = x / 4 | 2 (integer division) |
x %= 4 | x = x % 4 | 2 |
x++ | x = x + 1 | 11 |
Both x++ and ++x add one. Inside a larger statement they differ: x++ hands over the old value first, while ++x hands over the new value.
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = a++; // b gets the old value 5, then a becomes 6
int c = ++a; // a becomes 7 first, then c gets 7
cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
return 0;
}
a = 7, b = 5, c = 7
Mixing types and keeping decimals tidy
When you mix an int and a double, C++ converts the int automatically. Going the other way loses information: int cut = 3.99; stores 3, because the decimals are cut off, not rounded. To convert on purpose, use static_cast<double>(x).
#include <iostream>
using namespace std;
int main() {
int total = 391, subjects = 5;
double wrong = total / subjects; // integer division first
double right = static_cast<double>(total) / subjects; // convert, then divide
int cut = 3.99; // decimals are cut off, not rounded
char letter = 'A';
cout << wrong << " " << right << " " << cut << endl;
cout << letter << " " << int(letter) << " " << char(letter + 1) << endl;
return 0;
}
78 78.2 3
A 65 B
Doubles are close, not exact
A double is stored in binary, and a number like 0.1 has no exact binary form. So 0.1 + 0.2 is stored as 0.30000000000000004, and the test 0.1 + 0.2 == 0.3 is false. Never compare calculated decimals with ==. Check instead that the difference is tiny, for example smaller than 0.000001.
By default cout shows 6 significant digits, so 1234567.0 prints as 1.23457e+06. For money, use fixed and setprecision(2) from the iomanip header.
Simple interest
Simple interest is SI = P × R × T / 100. For ₹50,000 at 6% per year for 2 years, SI = 50,000 × 6 × 2 / 100 = ₹6,000, and the amount is ₹56,000. The program does the same sum.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double principal = 50000; // rupees
double rate = 6; // per cent per year
double years = 2;
double interest = principal * rate * years / 100;
double amount = principal + interest;
cout << fixed << setprecision(2);
cout << "Interest = Rs. " << interest << endl;
cout << "Amount = Rs. " << amount << endl;
return 0;
}
Interest = Rs. 6000.00
Amount = Rs. 56000.00
Key points
- A variable is a named place in memory with a type; declare it, give it a starting value and choose a meaningful name.
- Use
intfor whole numbers,long longfor big ones,doublefor decimals,charfor one character,boolfor true or false andstringfor text. - When both operands are integers,
/drops the decimal part; convert one operand todoublewhen you need the exact quotient. %gives the remainder,+=and++update a variable, and brackets make precedence clear.