0

Would you tell me why the output of this code is 5?

for(;i<5;i++){ i*=i; } System.out.println(i); }

9th Jul 2018, 2:23 AM
Afresia
Afresia - avatar
5 Answers
+ 5
When the loop starts, i is 0. Now, 0*0=0, and i remains 0. Then, i is incremented by 1. In the second iteration, 1*1=1, and there is an incrementation, so i becomes 2. In the third iteration, i first becomes 4 (2*2), and then becomes 5, due to the increment. In the fourth iteration, i is equal to 5, and the loop terminates. Thus, you get i == 5.
9th Jul 2018, 2:44 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Can you show the complete code? Did you initialize i prior to the loop?
9th Jul 2018, 2:32 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
0
I initialize i = 0
9th Jul 2018, 2:35 AM
Afresia
Afresia - avatar
9th Jul 2018, 2:35 AM
Afresia
Afresia - avatar
0
thank you Kinshuk Vasisht
9th Jul 2018, 2:47 AM
Afresia
Afresia - avatar