Sunday, August 2, 2009

Doubt in execution of if statement in C language!!!?

#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


main()


{


int a,b;


clrscr();


printf("enter the value for a:");


scanf("%d",%26amp;a);


printf("enter the value for b:");


scanf("%d",%26amp;b);


if(a-b)


{


printf("a is greater");


printf("\nThe value of a is:%d",a);


}


else


{


printf("b is greater");


printf("\nThe value of b is:%d",b);


}


getch();


}





The above program outputs only a is greater irrespective of the numbers entered as input. If b is greater it should give output as b is greater. But it is not so why? any help appreciated. Thank you.

Doubt in execution of if statement in C language!!!?
Yepp, it's if(a-b)





(a-b) returns a + resoult if a is greater than b, which is the interpreted as a logical YES


But if a is less than b than it returns a - value and only 0 in interpreted as a logical NO in C/C++, so it will not do anything.





Also you may want to check if (a==b) //if a equals b as if it does you won't get a result.








if(a==b)


printf ("a equals b");


else {


if (a%26gt;b)


{


printf("a is greater");


printf("\nThe value of a is:%d",a);


}


else


{


printf("b is greater");


printf("\nThe value of b is:%d",b);


}


}


getch();
Reply:I believe the error is "if(a-b)" it should be "if(a%26gt;b)"





I sure do prefer iostream.h and the cout and cin make things so,so much easier.
Reply:it's very simple. write if (a%26gt;b) instead of (a-b).


try it!


No comments:

Post a Comment