+ 2

Why is the output 26 and not 25?

For the following code: int x = 1; For (; x < 6; x++) x *= x; System.out.println(x); Why is the output 26? When x = 4, the loop checks the condition and since it passes, then it increments x to 5. Then x is squared to 25 and when the condition is checked again, the condition fails, but for some reason, increments x by 1 immediately after the loop termination giving you 26. But yet if it was just a regular loop with x, then x would just stop at 6 and not increment x once the loop Condition fails. Can someone explain the reasoning and logic behind this?

20th Nov 2019, 4:04 AM
JoeyCentral
JoeyCentral - avatar
9 Antworten
+ 14
x*=x (1) x++ (2) x*=x (4) x++ (5) x*=x (25) x++ (26) x<6 failed, loop terminated. prints 26 There you go
20th Nov 2019, 4:14 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 7
JoeyCentral You're welcome. Just remember that when a condition is satisfied, your code will be executed and then the variable will be incremented.
20th Nov 2019, 4:19 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 6
After the body of the loop in a given iteration, the incrementing is done before the condition check.
20th Nov 2019, 8:46 AM
Sonic
Sonic - avatar
+ 5
See when u enter the loop for first time initialization statement executes then condition is checked....... After that it executes as.... Body>loop expression (like x++) >check condition>body
20th Nov 2019, 4:13 AM
Saurabh B
Saurabh B - avatar
+ 5
Man 🌟Prometheus 🇸🇬 even mentioned values of x and I gave u the explanation... U think over it
20th Nov 2019, 4:17 AM
Saurabh B
Saurabh B - avatar
+ 4
U are correct with ur explanation upto x=25... After that for loop first increments x as x++...... Then it will check condition.... 26 < 6 it is False so loop is terminated
20th Nov 2019, 4:08 AM
Saurabh B
Saurabh B - avatar
+ 1
but the increment isnt executed if the condition doesnt hold true. it only increments if the condition check is returned true, which is why x is incremented to 5 after 4 is checked when x = 4
20th Nov 2019, 4:10 AM
JoeyCentral
JoeyCentral - avatar
+ 1
so why wouldnt x = 7 if that was the case and the loop was only incrementing x by 1 via the loop signature?
20th Nov 2019, 4:14 AM
JoeyCentral
JoeyCentral - avatar
+ 1
🌟Prometheus 🇸🇬 thank you for the answer! that answers everything now!
20th Nov 2019, 4:16 AM
JoeyCentral
JoeyCentral - avatar