Arithmetic Operators
Sooner or later, every program needs to do some math. Just like on paper, C++ gives you five arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), and modulo (%).
Addition, subtraction, and multiplication
Historically, programming languages use the symbol * for multiplication instead of × since this character isn’t available on a standard keyboard.
The operators +, -, and * behave exactly as you’d expect. Here’s a typical calculation you might write in any real program:
Division and integer truncation
Division in C++ uses the / operator. This is where C++ diverges from what you might expect.
When you divide two int values, the result is also an int. There’s no rounding: the decimal part is simply discarded.
You’ll see the output 2 and not 2.166....
If you actually need the decimal result, at least one of the two values must be a double (or another floating-point type):
The (double) cast tells C++ to treat that value as a double for this expression. Once one side of the / is a double, the other side gets promoted to a double automatically, and you get a decimal result.
The modulo operator
The % operator gives you the remainder after integer division. It only works on integers.
You’ll see the output 2 hours and 10 minutes.
The / operator gave us the whole hours; the % operator gave us what was left over. That pair, division and modulo together, is how you split a whole number into parts.
A few other places where % is genuinely useful:
1. Checking parity (even or odd)
You can check whether a number is even or odd by applying modulo 2:
A remainder of 0 means even; 1 means odd.
2. Wrapping around a bigger range to a smaller set
Say you have a fixed set of 7 values and you want to cycle through them repeatedly:
int index = some_number % 7;This always gives 0–6, no matter how large some_number is.
Operator precedence in arithmetic expressions
Operators like these act on values to form expressions, which C++ evaluates to a single result. C++ evaluates them in the same order you learned in school: multiplication and division before addition and subtraction.
int result = 2 + 3 * 4; // 14, not 20Multiplication runs first: 3 * 4 = 12, then 2 + 12 = 14.
Similarly, % has the same precedence as multiplication and division:
Both * and % are applied before +, giving 21.
Parentheses override the default order:
int result = (2 + 3) * 4; // 20When in doubt, add parentheses. They make the intent clear and prevent accidents.
Finally, when two operators share the same precedence, C++ evaluates them left to right. This is called left associativity. So 20 % 3 / 2 means (20 % 3) / 2, not 20 % (3 / 2).
Checkpoint
Given this code, what does it print?
int total = 9;
int count = 2;
double result = total / count;
std::cout << result << "\n";What does the % operator require that / does not?
Given this code, what does it print?
int result = 10 - 12 % 5 / 2;
std::cout << result << "\n";