Modulo
| Division (this is NOT modulo) | Modulo |
|---|---|
| 7 / 3 = 2 | 7 % 3 = 1 |
| 6 / 4 = 1 | 6 % 4 = 2 |
| -8 / 3 = -2 | -8 % 3 = -2 |
| 21 / 7 = 3 | 21 % 7 = 0 |
| 1 / 5 = 0 | 1 % 5 = 1 |
The modulo operator looks like this:
//It's this guy below
%It is used to get the remainder of division:
//The value of x after the code below runs is 0
//because 3 divides 3 evenly
x = 3 % 3
//The value of x after the code below runs is 1
//because 4/3 gives a remainder of 1
x = 4 % 3
//The value of x after the code below runs is 2
//because 5/3 gives a remainder of 2
x = 5 % 3
//The value of x after the code below runs is 0
//because 3 divides 6 evenly
x = 6 % 3
//The value of x after the code below runs is 1
//because 7/3 gives a remainder of 1
x = 7 % 3You seeing the pattern here? The pattern for anything modulo 3 is to cycle through 0, 1, and 2. There are 3 different possible answers, starting at 0 and going to 2.
This same pattern exists for any positive integer number. For example, anything modulo 5 will cycle through the numbers 0 to 4:
//0
z = 25 % 5
//1
z = 26 % 5
//2
z = 27 % 5
//3
z = 28 % 5
//4
z = 29 % 5
//0
z = 30 % 5