Sunday, September 1, 2013

Modulus Operator (%)

How to find remainders sign when one of the operand is negative??

When performing division it is very easy to find sign of quotient on the basis of elementary mathematics that if the two operands are of same sign then quotientwill be positive but negative in other case.

Now it feels cumbersome to us when we have to find the sign of remainder.It seems to us that the 'C' language is violating the rule of mathematics, But it is not actually true.
The mathematics is correct behind this , while our concepts have  proven to be weak.

In all opeartions of modiulus following ciondition should be satisfied:

a = ( ( a / b) * b) + (a % b)
i.e.
Dividend = Quotient * Divisor+ Remainder

From above equation

  Remainder = Dividend - Quotient * Divisor

 following the above equation we can calculate the remainder for following cases :
Finding remainder with negative opearnds 

Dividend||Divisor||Quoteint||Remainder

 10              3           3            1     // Remainder = 10- 3*3

-10             3          -3           -1     //Remainder = 10- {(-3)*3} 


 10            -3          -3            1     //Remainder = 10- {(-3)*(-3)} 

-10            -3           3           -1     //Remainder = -10- {3*(-3)} 


No comments:

Post a Comment