C++20 sections · 1024 units
Open in Course

The Modulo Operator

What is left over

The % operator returns the remainder after division. int rem = 7 % 2; stores 1 because 7 / 2 is 3 with 1 left over. This only works with integer types. If the dividend is smaller than the divisor, modulo returns the dividend.

int x = 3 % 5; stores 3 because 3 goes into 5 zero times with 3 remaining. Using modulo with zero crashes your program. int x = 7 % 0; triggers undefined behavior or a runtime error.

Always validate divisors before applying modulo.