+ 1
Why the result is 17?
ublic class main { 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
+ 5
1. Run:
i = 0 -> 0 + 0 = 0
2. Run:
i = 1 -> 0 + 1 = 1
3. Run
i = 2 -> 1 + 2 = 3
4. Run
i = 3 -> if-clause is now true -> 3 + 10 = 13
5. Run
i = 4 -> if-clause is false again -> 13 + 4 = 17
Now i is 5, therefore the loop terminates because the statement isnt true anymore.
And the final result is 17.
+ 9
when i is 1,2,4, it has been added to result.
result = 1+2+4 = 7
when i is 3, 10 is added.
result = 7+10 = 17