The Modulus Operator (%
)
Learn how we can use the modulus operator to get the remainder of integer division, and some common use cases.
In this short lesson, we'll explore how the modulus operator helps in obtaining the remainder after division. This has many applications and is particularly useful when we're solving problems using loops.
We can imagine that the answer to a division question like might be , with left over. This is an example of modular arithmetic.
Quotients and Remainders
When performing division using modular arithmetic, we get two results:
- The quotient, which is in this case
- The remainder, which is in this case
We've previously seen that modular division is the default form used in C++ when working with integers.
The /
operator lets us get the quotient:
// This will be 1
int Quotient { 5 / 3 };
To get the remainder, we use the modulus operator, denoted by %
:
// This will be 2
int Remainder { 5 % 3 };
A common use of the modulus operator is to check if a number is even or odd. After being divided by , an even number will have a remainder of , whilst an odd number will have a remainder of :
bool isEven(int Number) {
return Number % 2 == 0;
}
Test your Knowledge
Modulus Operator
After executing the following statement, what is the value of Remainder
?
int Remainder { 5 % 6 };
The Cycle of the Modulus Operator
One of the useful properties of modular arithmetic is its tendency to "wrap around" after they reach a certain value.
Let's see an example:
0 % 3; // 0
1 % 3; // 1
2 % 3; // 2
3 % 3; // 0
4 % 3; // 1
5 % 3; // 2
6 % 3; // 0
7 % 3; // 1
8 % 3; // 2
We can see a repeating pattern developing here. As we increment the left operand, the modulus operator returns a repeating cycle of . The length of this cycle is determined by the right operand. In this case, our right operand was , so we got a repeating pattern of 3 numbers.
If our right operand were we'd get a repeating cycle of and . Were it , our cycle would be
This repeating pattern is one of the main reasons that the modulus is useful in programming - particularly when paired with loops.
The Modulus Operator With Loops
The "wrapping around" nature of the modulus operator gives us an easy way to generate a boolean expression that is true on some subset of our loop iterations.
For example, if we increment a variable i
on every iteration of our loop, i % 3
will be 0
on every third iteration.
Below, we use this calculation within an if
statement to insert a line break on every third iteration:
#include <iostream>
using namespace std;
int main(){
for (int i = 1; i <= 9; ++i) {
cout << i << " ";
if (i % 3 == 0) cout << '\n';
}
}
1 2 3
4 5 6
7 8 9
The next lesson introduces a famous programming challenge where the modulus operator is crucial to solving the problem.
Fizz Buzz
Put everything we've learned in this chapter to the test by creating a C++ version of the Fizz Buzz game.