Modulo Operator (%) in C/C++ with Examples
Syntax: If x and y are integers, then the expression:
x % y
Produces the remainder when x is divided by y.
- If y completely divides x, the result of the expression is 0.
- If x is not completely divisible by y, then the result will be the remainder in the range [0, y-1]
- x mod y <x/2 if x>=y and x mod y=x if x<y
- If y is 0, then division by zero is a compile-time error.
Below is the C/C++ program to demonstrate the working of the modulo operator:
3 1 0
Restrictions of the modulo operator
The modulo operator has quite some restrictions or limitations.
The % operator cannot be applied to floating-point numbers i.e float or double. If you try to use the modulo operator with floating-point constants or variables, the compiler will produce an error.
Below is the C/C++ program to demonstrate the restrictions of the modulo operator:
Compilation Error in C code :- prog.c: In function 'main': prog.c:19:16: error: invalid operands to binary % (have 'float' and 'float') result = x % y; ^
Modulo Operator for negative operands
The sign of the result for the modulo operator is machine-dependent for negative operands, as the action takes as a result of underflow or overflow.
Below is the C/C++ program to demonstrate the modulo operator for negative operands:
-3 0 -3
Note: Some compilers may show the result of the expression as 1 and other may show -1. It depends on the compiler.