Noob question about 'for' and x=x*x | Sololearn: Learn to code for FREE!

0

Noob question about 'for' and x=x*x

In the case with the code below: public class Program { public static void main(String[] args) { for(int x=2; x<=10; x=x*x) { System.out.println(x); } } } May I ask why did it output 2 and 4 instead of 4? Or perhaps did I misunderstood x=x*x as 2*2 (equal 4), then the new x value (4) become 4*4 (equal to 16) which is invalid? Please let me know.

7/30/2019 7:34:18 PM

Rei

3 Answers

New Answer

+2

jyuuroku At the time of printing, the value of x is 2 first then it becomes 4. Then for the next iteration 4 is printed then value becomes 16 but 16 is not <= 10 so the loop exit.

+1

~ swim ~ Thank you very much!

+1