The modulo operator % with integers
What you'll learn: How to use the modulo operator to find the remainder of a division between two whole numbers.
The "Leftover" Operator
In your early school days, before you learned about decimals, you probably solved division problems using remainders. For example, if you tried to divide 7 cookies among 3 friends, everyone would get 2 cookies, and there would be 1 left over.
In C, the forward slash / performs division, but if you are working with integers, it throws away the remainder. To capture that "leftover" value, we use the modulo operator, represented by the percent sign %.
Think of % as the companion to /. While division tells you how many times a number fits into another, modulo tells you what couldn't fit.
How it works in code
The modulo operator only works with integers (int, char, long, etc.). If you try to use it with floating-point numbers like float or double, the compiler will give you an error.
Here is how you use it in a program:
#include <stdio.h>
int main() {
int totalCookies = 7;
int friends = 3;
int perPerson = totalCookies / friends; // Result: 2
int leftOver = totalCookies % friends; // Result: 1
printf("Each person gets %d cookies.\n", perPerson);
printf("There is %d cookie left in the jar.\n", leftOver);
return 0;
}
Why is this useful?
Modulo is surprisingly powerful in programming. Beyond just simple math, it is the primary tool for two common tasks:
- Checking for even or odd numbers: If you divide a number by 2 and the remainder (
% 2) is 0, the number is even. If the remainder is 1, it’s odd. - Keeping numbers in a range: Imagine a clock. After 12 comes 1, not 13. By using
% 12, you can ensure that a number "wraps around" back to the start once it reaches a certain limit.
It is a simple tool, but it is the secret ingredient for creating patterns, handling cycles of time, and organizing data into neat rows and columns.
Key takeaway
The % operator calculates the remainder left over after one integer is divided by another.