0
I don't understand this,
Why does this equal to 17 instead of 10. int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result);
3 Answers
+ 4
i = 0, result += i (0)
i = 1, result += i (1)
i = 2, result += i (3)
i = 3, result += 10 (13)
i = 4, result += i (17)
+ 3
int result = 0;
for (int i = 0; i < 5; i++) {
if (i == 3) {
result += 10;
}
else {
result += i;
}
}
The loop will execute 5 times in total:
First, i is 0:
if i==3? Nope, so the else part is executed:
result+=i; -> result=0+0 -> result=0
Then, i is 1:
if i==3? Nope, so the else part is executed again:
result+=i; -> result=0+1 -> result=1
Then, i is 2:
if i==3? Nope, so the else part is executed again:
result+=i; -> result=1+2 -> result=3
Then, i is 3:
if i==3? Yes!!
So the if part is executed: result+=10 -> result=3+10=13
Then, i is 4:
if i==3? Nope, so the else part is executed:
result+=i; -> result=13+4 -> result=17
Then i is 5 and the condition i<5 is no longer met, and the computer continues executing what it says after the for loop, which in our case is System.out.println(result), and since result has been assigned the value 17 last, our result is 17.
0
Thanks, for the answers