Thursday, June 05, 2008

What will be the output of the following C and Java programs?

C/JAVA:
int sum = 0;
for(int i=0;i<3;i++)
sum+=sum++;

Now print the value of sum

Answer...
C:
7
Java:
0

Why?...

3 comments:

Anonymous said...

Hello Gouuthaa....
see why ans 7 doesnt seem to require much logic... simple precedence knowledge gets u through to 7...
Now tell why 0 for Java code

Anonymous said...

Gouutha... the only explanation i can come up is this

sum += sum++ is computed left to right... as against right to left in C.
So sum always remains 0.
However sum+= ++sum will give 7...
Dont know whether ur getting the explanation.... But tats the only way i can think of... :D

Anonymous said...

that's right baby...