Step 3 of 6
Remainder with %
The % operator (called modulo or remainder) gives what's left over after an integer division.
#include <stdio.h>
int main(void) {
printf("%d %d\n", 17 / 5, 17 % 5);
printf("%d %d\n", 20 / 5, 20 % 5);
printf("%d\n", 9 % 2);
return 0;
}
3 2
4 0
1
17 divided by 5 is 3 with 2 left over (3 times 5 is 15, and 17 minus 15 is 2). / gives the 3 and % gives the 2. Together they always satisfy (a / b) * b + a % b == a.
What it's good for
- Even or odd:
n % 2is 0 for even numbers and 1 for odd ones. - Every Nth time:
i % 10 == 0is true for 0, 10, 20 and so on. - Wrapping around:
(hour + 5) % 24keeps a clock hour between 0 and 23. - Splitting units: 135 cents is
135 / 100dollars and135 % 100cents. The same trick splits seconds into hours, minutes and seconds.
% only works on integers. For doubles there's a library function called fmod, but you'll rarely need it.
Your turn: a match lasted 754 seconds. Print it as minutes and seconds: 12 min 34 sec.
Previous: The integer division trap Next: Shorthand operators