The modulo operator looks like this:
//It's this guy below
%It is used to get the remainder of integer division:
int x;
//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 % 3;You 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:
int z;
//0
z = 25 % 5;
//1
z = 26 % 5;
//2
z = 27 % 5;
//3
z = 28 % 5;
//4
z = 29 % 5;
//0
z = 30 % 5;When is the modulo operator useful?
At some point you might want to alternate between two values repeatedly. You could increment an integer and modulo it by 2:
int k = 0;
while(true) //the loop condition isn't important here, ignore it
{
// The value of x will alternate between 0 and 1
int x = k % 2;
++k;
}You could also accomplish this task by using a boolean variable and swapping it between true and false, but the modulo way works too!
There are a few other tricks regarding modulo that, if you make further headway in your programming journey, you might find useful… but that’s all I’ll say for now!