c aptitude array
#include<conio.h>
void main()
{
int a[]={0,1,2,3,4,5,6,7,8,9,10,11,12};
int num=0,i=0;
clrscr();
num=a[++i+a[++i]]+a[++i];
printf("%d",num);
getch();
}
how it produce output as 9
can u explain parsing of a[++i+a[++i]]+a[++i]
Member • Jul 25, 2011
Member • Jul 26, 2011
Member • Jul 26, 2011
Member • Jul 26, 2011
The logic is undeniable!!! 😲 But yeah, right!!! 😀nicepeeyushI encountered the same kind of problem few days ago. I had a statement like this and it was not showing the expected result. @praveen: i also thought that it should ork like this. But the real thing is ++i is not the whole statement so the value of i is not incremented at this place only. First the value of i is incremented in the whole statment i.e. it is incremented 3 times. So i becomes 3. Now wherever the compiler sees pre-incremented part(++x) it puts the final value and wherever it sees the post incremented part(x++), it puts the initial value. Now our statement:
a[++i+a[++i]]+a[++i]
Here all the "i"s are post incremented, so the final i.e. 3 will be posted.
a[3+a[3]]+a[3]
a[3+3]+3
a[6]+3
6+3
9
This is one of the examples why these kind of statements are avoided in programming.
You can take one more example....
int x=10;
y=x++ + x++;
Logically the output should be 21, but its 20 only.
You can try more examples like y=x++ + x++ + ++x;
P.S.: Correct me if i am wrong.
Member • Jul 26, 2011
Member • Jul 27, 2011
Member • Jul 27, 2011
Member • Jul 27, 2011
Member • Jul 28, 2011
Member • Jul 28, 2011
Member • Jul 28, 2011
Member • Oct 10, 2011
Member • Oct 16, 2011
#include<stdio.h> void main() { int num=0; printf("%d%d%d%d",num++,++num,num++,++num); getch(); }you make think that output of the program might be num++,++num,num++,++num executed in this way.you will execute from left to right.