The Mod Operator
-
Introduction
Suppose we have 10 students, and we need to arrange them into a few rows. Each row can have 4 students at most.
Here is what we will do:
- We assign 4 students to the first row, and then we have 6 students remaining.
- We assign another 4 students to the second row, and now we have 2 students left.
- The third row would only have the 2 remaining students
The Mod Operator
We can do the same calculation quickly using the “mod” operator.
It takes 2 input numbers A and B, and tells us what’s the remainder if we keep subtracting B from A.
If A is exactly a multiple of B, then the mod operator would return 0:
Example - Odd or Even Number
Suppose we need to know if a number is an “even” number or an “odd” number. We can calculate the mod of that number and 2. If the result is 0 (like “8 mod 2”), then the input is an even number; otherwise, the result has to be 1 (like “7 mod 2”), and that input number is an odd number: