0
For Loop
for (int i = 2; i < 10; i = i*i) { System.out.println(i); } here i = 2 then i < 10, i.e 2 < 10 is true then i x i and i is 2 also, i x i i.e 2 x 2 = 4 then loop must run 4 times right? but the answer is 2 Why 2, please explain.
2 Answers
0
The loop runs while i is less than 10.
The first run through i = 2 so it runs, then it multiplies i by i and stores that value in i.
The second run i = 4 (2x2 from the multiplying) so it runs again then multiplies i by i and stores that value in i.
The third run through i = 16 (4x4 from the multiplying) so it no longer runs the for loop.
Hope that helps, if you have any more questions or want it explained a little more feel free to let me know.
0
At the beginning you have i = 2
1st iteration i = 2 :
i < 10 -> 2< 10 which is TRUE and the loop runs
and the new i is:
i = 2*2 = 4
2nd iteration with i = 4 :
4 < 10 which is TRUE and the loop runs
and the new i becomes:
i = 4*4 = 16
In the 3rd iteration, i = 16 :
16<10 is FALSE and the loop stops here
So the loop runs only 2 times.
Hope that helps