I have :
#include <stdio.h>
int main(void) {
int s,i,t[] = { 0, 1, 2, 3, 4, 5 };
s = 1;
for(i = 2; i < 6 ; i += i + 1)
s += t[i];
printf("%d",s);
return 0;
}
Why is the result 8?
What I'm thinking:
first loop: 2<6 True
i+=i+1 is 5
s=1+t[5] =>1+5=6
second loop : 5<6 True
i=5+5+2=11
s=6+t[11]???
I will guide you to the for
loop reference:
iteration-expression is evaluated after the loop body and its result is discarded. After evaluating iteration-expression, control is transferred to cond-expression.
In your example, i += i + 1
, which is the iteration expression we're talking about, is evaluated after the loop body.
Taking this into account, the result will be 8