For loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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); } } }

15th Aug 2022, 11:34 PM
NPCcode
NPCcode - avatar
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.
16th Aug 2022, 12:29 AM
A͢J
A͢J - avatar
+ 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
16th Aug 2022, 2:50 AM
Mauricio Martins
Mauricio Martins - avatar
+ 1
NPCcode x+=x 2 2+2 = 4 4 +4 = 8 This will run your for loop code 3 times.
16th Aug 2022, 3:53 AM
BroFar
BroFar - avatar
+ 1
I see, thank you for answering guys
16th Aug 2022, 3:58 AM
NPCcode
NPCcode - avatar