0

Puzzle: Why does a for loop using the increment statement "x =+ 2" run forever?

Suppose you want to iterate through the even natural numbers from 2 to 10. You could use the following code: public class Program { public static void main(String[] args) { for(int x = 0; x <= 10; x += 2) { System.out.println(x); } } } /* Output: 0 2 4 6 8 10 */ However, when you change the increment statement to x=+2 the loop never ends. Why?

2nd Jan 2017, 11:36 AM
Christian Wiesner
3 odpowiedzi
0
because =+2 is not the correct syntax for increment, so x value is not incremented. So the loop is infinite!
2nd Jan 2017, 11:33 AM
ifl
ifl - avatar
0
x=+2 actually sets x to 2 (rather the intended increment of x)
2nd Jan 2017, 11:35 AM
ifl
ifl - avatar
0
Thanks a lot!
2nd Jan 2017, 11:37 AM
Christian Wiesner