0

Strange for loop

Hi, can somebody please explain this for loop, i.e. the value of int i in individual steps? int i=0; for(;i<4;i+=2) { i = i*i; cout << i << endl; } cout << i << endl; To me it seems a bit odd that the output is 0 4 6 <-- why was the i incremented?

23rd Oct 2016, 8:25 AM
Milan Novotny
Milan Novotny - avatar
2 Respostas
+ 2
i was incremented because the increment is done at the end of the loop before checking the condition. Step by step: i = 0 0 is below 4, so we enter the for loop i = 0*0 = 0, and 0 is printed i is incremented to 2 2 is below 4, we loop again i = 2*2 = 4, and 4 is printed i is incremented to 6 6 is not below 4, we exit the loop 6 is printed Equivalent while loop: int i=0; while(i<4) { i = i*i; cout << i << endl; i+=2; } cout << i << endl; In general, it's better to use a while loop over a for loop if you modify the loop variable inside the loop (besides the increment) to avoid confusion.
23rd Oct 2016, 8:35 AM
Zen
Zen - avatar
0
Thank you! Great answer.
23rd Oct 2016, 8:50 AM
Milan Novotny
Milan Novotny - avatar