Blog Moved

This website completely moved to new domain. For latest content, visit www.programmingposts.com

Search This Blog

10 Nov 2012

% OPERATOR/ MOD OPERATOR IN C

% OPERATOR IN C :
-----------------------------------
-> % OPERATOR is to get the remainder when a number is divided with any other number.
   
   Example: int a=10%2; then the a value is zero. because the when 10 is divided by 2   
      the remainder is zero.
     
 int a=10%2; Here 10 is numerator and 2 is denominator.

-> When the  numerator is less than the denominator, then the result of the % operator is
      numerator value. 
     Example: int a=2%10; Here the numerator 2 is less than the denominator 10. Hence  
     a value will be 2. 

-> We cannot apply mod % operator on the floating values. It will generate compile time
      error. 
-> There is a special function " fmod() " for applying % operation on float.
-> Whenever we are performing mod % operation on any two operands then the resultant
     sign is equivalent to numerator sign.

     int a=-10%3; Then the result is a=-1 as the sign of numerator
                10 is negative.

Examples to understand the operation of % operator:

1) int a=1%10;
   printf("%d",a);
  output:1
-------------------------
2) int a=2%10;
   printf("%d",a);
  output:2
--------------------------
3) int a=3%10;
   printf("%d",a);
  output:3
--------------------------
4) int a=10%3;
   printf("%d",a);
  output:1
--------------------------
5) int a=10%4;
   printf("%d",a);
  output:2
---------------------------
6)int a=10%2;
   printf("%d",a);
  output:0
---------------------------
7) int a=-10%3;
   printf("%d",a);
  output:-1
-------------------------
8) int a=10.0%3;
   printf("%d",a);
  output: Error. As % operator cannot be applied on float.
--------------------------
9) int a= -10%-3;
   printf("%d",a);
  output: -1 
  (As the result sign is same as numerator sign)
------------------------------
10) int a=10%3.0;
   printf("%d",a);
  output: Error.As 3.0 is float and cannot be used in 
          % operation.

1 comment: