+ 2
Some body explain to me how the output of this java code is 17
public class Program { public static void main(String[] args) { int result=0; for (int i=0; i<5; i++) { if (i == 3) { result+=10; } else { result+=i; } } System.out.println(result); } }
2 Answers
+ 7
Basically, the for loop iterates through the values 0, 1, 2, 3 and 4.
The first value is 0. As it is not 3, result = 0 + 0 = 0.
The next value is 1. As it is also not 3, result = 0 + 1 = 1.
Next is 2. Which is also not 3, so result = 1 + 2 = 3.
Next value is 3, hence 10 (instead of 3) is added. Result = 3 + 10 = 13.
Finally, we have 4. It is not equal to 3, so result = 13 + 4 = 17.
+ 21
i=0; result=0
i=1; result+1=1
i=2; result+2=3
i=3; result+10=13
i=4; result+4=17
So, result = 17