Thursday, July 9, 2009

Output of a C++ program?

#include %26lt;iostream%26gt;


using namespace std;


int main()


{


int a = 6, b = 6, c = 20;





if (a++ %26lt;= --b %26amp;%26amp; c != b)


c += 5;


else if (a %26gt;= ++b)


c = a++ * b-- + 3;


else


c += 50;





c = a + b + c - 10;





cout %26lt;%26lt; "a = " %26lt;%26lt; a %26lt;%26lt; endl;


cout %26lt;%26lt; "b = " %26lt;%26lt; b %26lt;%26lt; endl;


cout %26lt;%26lt; "c = " %26lt;%26lt; c %26lt;%26lt; endl;





return 0;


}





Can someone explain to me why the output of a,b, and c is 8,5,and 48 respectively?

Output of a C++ program?
we come to


if (a++ %26lt;= --b %26amp;%26amp; c != b)





first b is pre-decremented


now a=6 b=5 c=20





now the "if" expression is evaluated, which, translates to


(6 %26lt;= 5 %26amp;%26amp; 20 != 5)


which evaluates to false





now the post-increment on a is applied


now a=7 b=5 c=20





since the "if" evaluated false, we now evalutate the "else if"...





first b is pre-incremented


now a=7 b=6 c=20





now the expression is evaluated, which, translates to


(7 %26gt;= 6)


which is true, so we execute the line of code


c = a++ * b-- + 3;


which translates too


c = 7*6+3


now a=7 b=6 c=45


now the post-increment on a is applied, and, the post-decrement on b is applied.


now a=8 b=5 c=45





the "else" is skipped





now c = a + b + c - 10 is executed, which, translates to


c = 8 + 5 + 45 - 10


now a=8 b=5 c=48

baby breath

No comments:

Post a Comment