The Modulus Operator: Finding Remainders
You'll learn how the % operator computes remainders and use it to solve practical problems like detecting even or odd numbers.
What Is the Modulus Operator?
The modulus operator (%) returns the remainder after division. While / tells you how many times one number fits into another, % tells you what's left over.
Think of it like sharing cookies: if you have 10 cookies and 3 friends, each friend gets 3 cookies (10 / 3 = 3), but 1 cookie remains (10 % 3 = 1).
Basic Syntax
int remainder = 10 % 3; // remainder is 1
int leftover = 17 % 5; // leftover is 2
int none = 20 % 4; // none is 0 (divides evenly)
The Even/Odd Pattern
The most common use of % is detecting even or odd numbers. Any number divided by 2 leaves a remainder of either 0 (even) or 1 (odd):
int a = 8;
int b = 7;
int resultA = a % 2; // 0 (even)
int resultB = b % 2; // 1 (odd)
Works With Negative Numbers
The result's sign matches the dividend (first number):
int x = -10 % 3; // -1
int y = 10 % -3; // 1
int z = -10 % -3; // -1
Common Use Cases
- Cycling through ranges:
index % arrayLengthwraps values - Every nth item:
counter % n == 0triggers every n iterations - Last digit extraction:
number % 10gives the rightmost digit
Key Takeaway: The modulus operator % returns the remainder after division, making it perfect for detecting patterns like even/odd numbers or cycling through fixed ranges.