How the output of these code is 4??? I had asked these questions in challenge. | Sololearn: Learn to code for FREE!
+ 2

How the output of these code is 4??? I had asked these questions in challenge.

int i; for(i = 0; i < 3; i+= 2){} System.out.print(i);

30th Apr 2017, 4:06 PM
Hasrat Wadsariya
Hasrat Wadsariya - avatar
7 odpowiedzi
+ 14
In the for loop... Initially i=0 then i=i+2(i becomes 2) condition is still satisfied as i<3(I.e 2<3) then again i=i+2(means 2+2=4) now it checks whether i<3 or not and as it is not the loop terminates , therefore i=4 is the final value of i which is printed by System.out.print()
30th Apr 2017, 4:20 PM
‎‏‎‏‎Kueen
‎‏‎‏‎Kueen - avatar
+ 12
Make It Yourself... I think my explanation was not clear. Well as I mentioned earlier i inside the loop was 2 the condition is valid , now see in next iteration it got incremented by 2 that means it becomes 4. Now notice that i=4 is greater than 3 which isn't valid , so it is not accepted, that's why the loop terminates and the final value of i is 4 only.
1st May 2017, 2:11 PM
‎‏‎‏‎Kueen
‎‏‎‏‎Kueen - avatar
+ 2
Observe that the system.out.println is not inside the for loop. Tha is why when the loop is finished the i=4 and then it is printed.
30th Apr 2017, 4:09 PM
John Kary
John Kary - avatar
+ 2
Observe also that the counter is i+=2 not i++ .
30th Apr 2017, 4:21 PM
Hassen Basdouri
Hassen Basdouri - avatar
+ 2
thanks ,now I have no query kueen indian
1st May 2017, 2:14 PM
Hasrat Wadsariya
Hasrat Wadsariya - avatar
+ 1
but kueen indian i want to be less than 3 so how 4 is accepted
30th Apr 2017, 4:59 PM
Hasrat Wadsariya
Hasrat Wadsariya - avatar
0
It is not accepted in the for loop,because it is not < 3 but that doesnt change the fact that the value of i=4
30th Apr 2017, 5:06 PM
John Kary
John Kary - avatar