Arithmetic operators
- C++ course
- Beginner
- Lesson 24/116
- 4 min
Learn basic arithmetic with +, -, *, / and %.
Arithmetic operators
C++ has five basic arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division) and % (modulo, remainder). The first four work like in math.
The % operator gives the remainder of division: 17 % 5 = 2 because 17 = 3 × 5 + 2. Modulo works only with integers.
Division depends on the operand types: 7 / 2 = 3 (int), 7.0 / 2.0 = 3.5 (double). For a decimal result, at least one operand must be double.
Increment and decrement
The ++ and -- operators add or subtract 1 from a variable. x++ means the same as x = x + 1.
These operators can be prefix or postfix: ++x (increment first) and x++ (increment after). Both add 1 to x, but they differ when used inside an expression.
In y = x++;, x is assigned to y first, then incremented. In y = ++x;, x is incremented first, then assigned to y. To avoid confusion, use them standalone when possible.
Practice Print arithmetic results
Inside main, declare four int variables: sum = 10 + 5, diff = 10 - 3, product = 4 * 6, remainder = 17 % 5. Print each on its own line with std::cout using std::endl.
Starter code
#include <iostream>
int main() {
// Declare four arithmetic operations
// Print each with std::cout
return 0;
}Sample solution
#include <iostream>
int main() {
// Declare four arithmetic operations
int sum = 10 + 5;
int diff = 10 - 3;
int product = 4 * 6;
int remainder = 17 % 5;
// Print each with std::cout
std::cout << sum << std::endl;
std::cout << diff << std::endl;
std::cout << product << std::endl;
std::cout << remainder << std::endl;
return 0;
}Expected output
15 7 24 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the result of 10 % 3?
- 1 Correct answer
- 3
- 10
- 0
Explanation: 10 = 3 × 3 + 1, the remainder is 1.
2 Modulo operator
int remainder = 17 ____ 5;
int remainder = 17 % 5;
Explanation: The % operator gives the remainder.
3 Match operators
| Term | Meaning |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
% |
Remainder |