How does this be an infinite loop? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

How does this be an infinite loop?

class MyClass { public static void main(String[ ] args) { for(int i=0;i<5;){ i=i++; System.out.print(i); } } }

21st May 2018, 7:20 AM
Tilanka Dilshan Senadheera
Tilanka Dilshan Senadheera - avatar
2 ответов
+ 8
I think its becuase your assigning "i" to use the value of "i" again before an increment is made so the value of i would be 0 again and again giving you your infinate loop. If you use ++i instead your output will be diffrent as the increment is made before hand.
21st May 2018, 7:37 AM
D_Stark
D_Stark - avatar
+ 7
Because of the line where it says i = i++; the variable 'i' value is 0, and in that line you assign the value (zero) back to 'i' itself, again and again. Remember that when you go i = i++; the value of 'i' is assigned (to itself) before it is incremented, contrary, had you used i = ++i; the value is incremented first, before it is assigned. Hth, cmiiw
21st May 2018, 7:37 AM
Ipang