Coders4fun Quiz #1
Tags:
What will be printed using this c++ code?
#include <iostream>
int main()
{
int i = 0;
for (i = i == 0; i < 9; i = 1 + i * 2);
std::cout<<i<<std::endl;
return 0;
}
Please don’t cheat using a compiler!
P.S.
Of course the example compiles!
Se sei interessato a questo post, potresti anche provare a leggere:
- No related posts
15 Oct 2007 dzamir
2
3
7
3,5,7
1 + i * 2 is the generic representation for odd numbers where i is an integer
You are all wrong!!
0
1
3
7
I’m guessing the i==0 creates i=1 initially
Tricky one, but I think it’s:
15
I think Anirudh is right about the i==0 being 1, but there’s a semicolon after the for-loop. The for-loop is only calculating “i”, but it is not printing anything on the screen. The output is after the loop.
@Jelle:
This is the right answer, congratulations 
Good.. good!
Ok i will explain the solution:
The for assignement i = i == 0 says:
assign to i the value (i is equal to 0), then if i is 0, the condition is true (1) and i will be 1.
The for loop has a semicolon, so it only executes the for without the cout instruction, that will be executed ad the end of the for.
Let’s calculate i values in the for-loop:
Initial value:
1
Second value:
i = 1 + i * 2 = 1 + 1 * 2 = 3
Third value:
i = 1 + 3 * 2 = 7
Fourth value:
i = 1 + 7 * 2 = 15
Now the for condition (i < 9) is not respected and the for will exit.
Then the cout will print 15
That’s nasty! I missed the semicolon too, so my answer (what I’d actually typed into a terminal) was “1,3,7 # 15″ … I’d written down the right answer, but at the wrong side of the #comment!
Rats! I got the i==0, but I missed the semi-colon…
Nice quizz, thanks!
This was nice. More of these, please!