Its resulting in an infinte loop...why so? can we use ternary operator in increment part?

public class Program { public static void main(String[] args) { for(int x=0; x<=10; x=(x<5)?x+2:x++) { System.out.println(x); } } }

3/24/2020 10:22:01 PM


2 Answers

New Answer


yes, you can use ternary operator there replace 'x++' by '++x' there to make it a finite loop as after crossing 5, x=x++ which is equivalent to x=x only resulting in infinite loop.


An alternative is to declare another variable inside the loop init for (int x=0, y=0; x <= 10; x+=2, y++) System.out.printf("x =%d, y=%d\n", x, y);