+ 11
Can somebody explain why the output of this code 17?
int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result);
3 Answers
+ 21
Normally it loops through and adds i to result, except when i is 3, in which case it adds 10. Here it is:
Loop # i val. result val.
1. 0. 0
2. 1. 1 (0+1)
3. 2. 3 (1+2)
4. 3. 13 (3+10 because i is 3)
5. 4. 17 (13+4)
6. 5. i is not < 5 so the loop body is not executed. It exits the loop and prints result, which is 17. I hope this helps.
+ 20
thank you.
+ 10
Thanks