Recognizing when to use the modulus operator

Codebug picture Codebug · Apr 9, 2010 · Viewed 26.1k times · Source

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?

I know I can use the modulus operator to see whether a number is even or odd and prime or composite, but that's about it. I don't often think in terms of remainders. I'm sure the modulus operator is useful, and I would like to learn to take advantage of it.

I just have problems identifying where the modulus operator is applicable. In various programming situations, it is difficult for me to see a problem and realize "Hey! The remainder of division would work here!".

Answer

Paul R picture Paul R · Apr 9, 2010

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;