![]() |
VOOZH | about |
The modulo operator (%) is an arithmetic operator used in C and C++ to find the remainder after dividing one integer by another. It returns the leftover value of an integer division operation.
10 % 3 = 1
If x and y are integers, then the expression:
x % y;
pronounced as "x mod y". For example, 10 % 2 will be pronounced as " Ten mod Two".
If 10 % 3 is calculated, the result is 1 because dividing 10 by 3 leaves a remainder of 1. Similarly, 8 % 2 returns 0, which indicates that 8 is an even number.
To understand operators and their applications in algorithms, check out our Complete C++ Course, where you’ll learn how to use various operators and functions effectively in C++.
The modulo operator has few restrictions or limitations on it. The % modulus 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.
Output
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;
^
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.
-3 0 -3
Note: In C and C++, the sign of the result follows the sign of the dividend (left operand).
Example
-10 % 3 = -110 % -3 = 1The modulo operator is widely used in programming for mathematical calculations, looping operations, and data processing tasks.