+ 1
why this ouputs 2?
int i = 0; for (;i<4;i+=2){ i=i*i; } cout << i%4; //2 ? I thought it should be 0, for the exit value of the loop is 4??
4 Antworten
+ 4
At the end of the loop the value of i is 6 because in the loop you assign to it the value of 4, then increase it by 2 so it gets the value of 6 and fails to enter the loop again. So 6%4 prints 2.
+ 1
i = 0 before entering the loop.
i enters loop 1 as: 0.
Then exits as: 0 + 2.
i enters loop 2 as: 2.
Then exits as: 4 + 2.
Thus failing the For loop condition of i<4.
+ 1
first loop
i = 0, i<4, i = 0*0
second loop
i = 0 + 2, i<4, i = 2*2
third loop
i = 4 + 2, 6 NOT lower than 4 DOESN'T ENTER FOR.
i stays with value 6 and cout command follows.
As you can see after the end of one loop, the first thing is to increase it and then check the bsc.
Think that if you hadn't assign i in for loop, it would work like that:
first loop
i = 0, i < 4, do something
second loop
i = 0+2, i < 4, do something
third loop
i = 2+2 end of loop
Variable i changes both in the check of for and inside the for. If you don't want that, you have to use one more variable.
+ 1
Thanks for explanation! I missed the basic knowlege about the for loop algoritm. And I realize that it actually runs the statement (between brakets) before incrementing the value in the 3 rd for loop stage. Now it is more clear, thank you very much.