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?
3 Antworten
0
because =+2 is not the correct syntax for increment, so x value is not incremented. So the loop is infinite!
0
x=+2 actually sets x to 2 (rather the intended increment of x)
0
Thanks a lot!