Arithmetic Operators
beginnerWhat you'll learn
- Evaluate arithmetic expressions with correct precedence.
- Predict when integer division truncates.
- Update a value with a compound assignment operator.
C++ provides five basic arithmetic operators for performing mathematical calculations on numeric types.
Start With a Problem
You want to split a bill of 100 among 3 people. A calculator shows 33.33, but the same expression in C++ with whole numbers gives 33, because both operands are ints and the fraction is discarded.
Arithmetic in C++ depends on the types involved. The rest of this note covers each operator and how integer and floating-point math behave.
Watch for these in class: = vs == in conditions, a stray ; after if/for, uninitialized variables, and confusing & (bitwise) with && (logical). Demo each one live before students hit it.
Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division | 10 / 3 | 3 |
% | Modulus | 10 % 3 | 1 |
Integer Division
When both operands are integers, the decimal part is discarded (truncated toward zero).
Modulus with Negative Numbers
The sign of the modulus result follows the dividend (left operand).
Floating-Point Division
If at least one operand is a floating-point type, the result is a floating-point division.
Operator Precedence
The multiplicative operators (*, /, %) have higher precedence than the additive operators (+, -).
Common mistakes: integer division truncates (7 / 2 is 3) and dividing an integer by zero is undefined behavior.
Complete Program: Arithmetic Operators
Key takeaway: Always use parentheses to clarify operator precedence — readable code is better than clever code, and integer division silently truncates toward zero.
Try it: Write an expression that calculates the remainder when 17 is divided by 5, and print the result.