+ 4

How this outputs 1??

public class Program { public static void main(String[] args) { int i=3; for(i=5;i<i*i;i--){} System.out.print(i); } }

26th Feb 2018, 12:21 PM
Rishabh
Rishabh - avatar
2 ответов
+ 4
iteration 1: i=5 -> i < 25 is true. iteration 2: i=5 -> i-- so i=4 -> 4 < 16 is true. iteration 3: i=4 -> i-- so i=3 -> 3 < 9 is true. iteration 4: i=3 -> i-- so i=2 -> 2 < 4 is true. iteration 5: i=2 -> i-- so i=1 -> 1 < 1 is FALSE. End of the for loop with i=1; System.out.print(i) is out of the for loop so it prints 1
26th Feb 2018, 12:31 PM
J Domingo Jiménez J
J Domingo Jiménez J - avatar
+ 12
for () loop will keep on executing until the condition i <i*i will be true ... so we are not going to see each loop (it will consume time) , but just see when the condition become false for the 1st time ... here at 1 <1 , so 1 will be the final value of i after loop executes fully
26th Feb 2018, 12:34 PM
Gaurav Agrawal
Gaurav Agrawal - avatar