Sunday, September 1, 2013

Division operator in c (Carefully divide)

Division Operator(/)

Integer division:
If two operands performing division operation are integer then the result will be an integer iwith truncated decimal values.

e.g.

a=10; b=3;
then  a/b = 3 ;  (rather than 3.333 in normal algebra.)


Ques. What will be the output of the following programme?

#include<stdio.h>
int main()
{
   float c;
 
    printf("%d\n", 10/3);
    printf("%f\n", 10/3);
    c=10/3;
    printf("%f\n",c);


return 0;

    }

output: 



 

3
0.000000 
3.000000

Notice that  all three expressions has both integers but all three expressions are having different outputs. all three expressions are performing integer division hence output first will be integer.

That is 10/3 =3 in short.


If one of the operands in division operation are float then result will be float.

#include<stdio.h>
int main()
{
   float c;    printf("%d\n", 10.0/3);
    printf("%f\n", 10.0/3);
    c=10.0/3;
    printf("%f\n",c);
  
    printf("%d\n", 10/3.0);
    printf("%f\n", 10/3.0);
    c=10/3.0;
    printf("%f\n",c);
  
    printf("%d\n", 10.0/3.0);
    printf("%f\n", 10.0/3.0);
    c=10.0/3.0;
    printf("%f\n",c);
  

            return 0;
   }


 Ans.


-1431655765
3.333333
3.333333

-1431655765
3.333333
3.333333

-1431655765
3.333333
3.333333

No comments:

Post a Comment