This is a quick lesson on the Modulus Operator, which will return the "remainder" of dividing two integers.
This might seem quite niche, but turns out to be incredibly useful for programming.
We can imagine that the answer to a division question like might be , with left over.
is the quotient and is the remainder.
We've previously seen how the division operator, /
lets us get the quotient:
// This will be 1
int Quotient { 5 / 3 };
The modulus operator, denoted by the %
character, is how we get the remainder:
// This will be 2
int Remainder { 5 % 3 };
The modulus operator is only used with integers, and almost exclusively positive integers. Because of this, the return type of the modulus operator will also be an integer.
A common use of the modulus operator to check if a number is even. Only even numbers have no remainder after being divided by :
bool isEven(int Number) {
return Number % 2 == 0;
}
int Remainder { 5 % 6 };
After executing this statement, what is the value of Remainder
?
Lets consider some more examples of what the modulus operator will return:
int Result0 { 0 % 3 }; // 0
int Result1 { 1 % 3 }; // 1
int Result2 { 2 % 3 }; // 2
int Result3 { 3 % 3 }; // 0
int Result4 { 4 % 3 }; // 1
int Result5 { 5 % 3 }; // 2
int Result6 { 6 % 3 }; // 0
int Result7 { 7 % 3 }; // 1
int Result8 { 8 % 3 }; // 2
int Result9 { 9 % 3 }; // 0
int Result10 { 10 % 3 }; // 1
int Result11 { 11 % 3 }; // 2
We can see a repeating pattern developing here as we increment the left operand.
We've been using the word operator to describe the syntax representing addition +
, subtraction -
, modulus %
and more.
The ++
in this code is an operator:
i++;
Operands are the inputs to the operator.
For example, in an expression like i++
, the operator is ++
and the operand is i
.
In an expression like 8 % 3
, the operator is %
, the left operand is 8
and the right operand is 3
.
This repeating pattern is the main reason modulus is useful in programming - particularly when paired with loops.
For example, if we wanted to do something on every 10th iteration of a loop:
for (int i = 1; i <= 50; i++) {
cout << i << " ";
if (i % 10 == 0) cout << endl;
}
The above code inserts an endl
on every 10th iteration. The output looks like this:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
The next lesson introduces a challenge where the modulus operator is very helpful.
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way