Recognizing when to use the modulus operator

Solution 1:

Imagine that you have an elapsed time in seconds and you want to convert this to hours, minutes, and seconds:

h = s / 3600;
m = (s / 60) % 60;
s = s % 60;

Solution 2:

0 % 3 = 0;
1 % 3 = 1;
2 % 3 = 2;
3 % 3 = 0;

Did you see what it did? At the last step it went back to zero. This could be used in situations like:

  1. To check if N is divisible by M (for example, odd or even) or N is a multiple of M.

  2. To put a cap of a particular value. In this case 3.

  3. To get the last M digits of a number -> N % (10^M).

Solution 3:

I use it for progress bars and the like that mark progress through a big loop. The progress is only reported every nth time through the loop, or when count%n == 0.