0
For loop
I just started learning java, and a little confused if why this loop only runs 2 times, in my expectation this should run 3 times. Can someone kindly explain some answers. Thank you public class Program { public static void main(String[] args) { for(int x=2; x<10; x=x*x) { System.out.println(x); } } }
4 Answers
+ 3
Because after x = 2, x = x * x = 2 * 2 = 4
So 4 < 10 true
After 4, x = 4 * 4 = 16
So 16 < 10 false and loop will be break.
+ 1
you can understand the *for* loop as this:
```
// init part
int x=2;
// condition check
while(x<10) {
// your block
System.out.println(x);
// increment/decrement/loop expression
x=x*x
}
Having this way, and looking the previous comment you'll understand what's going on... basicaly in second interaction, x is becoming 16, thus breaking the loop
+ 1
NPCcode x+=x
2
2+2 = 4
4 +4 = 8
This will run your for loop code 3 times.
+ 1
I see, thank you for answering guys