C/C++ Arena

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

% 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