+ 2

I don't understand why

What is the output of the following code? int f=1, i=2; while(++i<5) f*=i; System.out.println(f); //output is 12 may you please explainto me why?

25th Feb 2018, 9:58 PM
Ehab Al-Ani
Ehab Al-Ani - avatar
3 odpowiedzi
+ 18
it will work for 3 and 4 cycle1) 3 <5 [true] ... f*=3 ==> f=1*3=3 cycle2)4 <5 [true] ... f*=4 ==> f= 3*4= 12 //then loop stops as ++4 ... ie 5 is not smaller than 5
26th Feb 2018, 2:32 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 6
In the beginning i value was 2, as it enters the loop it increases immediately to 3 due to the pre-increment, in the loop body f is multiplied by i (1*3 so f=3) then i is again increased to 4, and f is again multiplied by i, by then f value was 3 (3*4 so f=12), the next time it is checked in while() i is incremented again to become 5, the loop ends because the condition is false (i is no longer less than 5) and f was outputted to the screen with its value=12. Hth, cmiiw
25th Feb 2018, 10:20 PM
Ipang
+ 3
Thanks a lot
25th Feb 2018, 11:37 PM
Ehab Al-Ani
Ehab Al-Ani - avatar