syntax: dividend % divisor
for example:
5%2 give us 1 because when we divide 5 by 2 we get 2 as quotient and 1 as the remainder.
Similarly,
5%3 give us 2 because when we divide 5 by 3 we get 1 as quotient and 2 as the remainder.
Let’s take a look at the internal calculation of ‘%’ operator :
x%y will be resolved as x-(x/y)*y
for example, suppose x = 5 and y = 2, then
x%y >> x-(x/y)*y
5%2 >> 5-(5/2)*2
>> 5-(2)*2
>> 5-4
>> 1
So, 5%2 is 1.
Points to remember regarding the ‘%’ operator :
- When the dividend is greater than the divisor, it will give the remainder.
10%3 = 1
- When the dividend is smaller than the divisor, then the dividend itself is the remainder.
3%10 = 3
- For modulo division, the sign of the result is always the sign of the first operand i.e. dividend.
e.g.
-10%3 = -1
-10%-3 = -1
10%-3 = 1
10%3 = 1,
This is so because modulo operation is solved as :
x%y => x-(x/y)*y
suppose x=-10 and y=3 ,then
-> -10 -(-10/3)*3
-> -10 -(-3)*3
-> -10 + 9
-> -1
thus, -10%3 is -1