Take a look at the console below. What do you think the %
operator does?
The %
performs a "modulus operation." Modulus operations give the remainder of division problems.
Below is a table that captures the same information that we were calculating in the console above:
Problem Division answer Division remainder Mod answer
0 / 4 0 0 0
1 / 4 0 1 1
2 / 4 0 2 2
3 / 4 0 3 3
4 / 4 1 0 0
5 / 4 1 1 1
6 / 4 1 2 2
7 / 4 1 3 3
8 / 4 2 0 0
9 / 4 2 1 1
10 / 4 2 2 2
11 / 4 2 3 3
12 / 4 3 0 0
13 / 4 3 1 1
14 / 4 3 2 2
15 / 4 3 3 3
16 / 4 4 0 0
17 / 4 4 1 1
Take a look at that: the division remainder and mod answer columns are precisely the same!
You might use modulus operations every day if you look at an analog clock: there, the hour hand swings from 1 to 12, even though there are 24 hours in the day. So when it's 5pm, it's the 17th hour of the day: 12 + 5 = 17
and 17 % 12 = 5
If you'd like to try another clock-math exercise to sharpen your mod skills, here's a good one.
Fill in the "Division remainder" and "Mod answer" columns of the below table. If you like, type the mod problem into the console:
Problem Division answer Division remainder Mod answer
0 / 5 0 ? ?
1 / 5 0 ? ?
2 / 5 0 ? ?
3 / 5 0 ? ?
4 / 5 0 ? ?
5 / 5 1 ? ?
6 / 5 1 ? ?
7 / 5 1 ? ?