C++20 sections · 1024 units
Open in Course

Modulo Use Cases

Practical applications

You detect even or odd with % 2. If x % 2 == 0, then x is even. If x % 2 == 1, then x is odd. This works because even numbers divide by 2 with no remainder. Modulo wraps values into a range.

int index = (i + 1) % 10; keeps index between 0 and 9. When i is 9, (9 + 1) % 10 is 0, wrapping back to start. You can extract digits using modulo. int lastDigit = num % 10; gets the ones place.

Dividing by 10 shifts right: num = num / 10; removes the last digit.