0

I don't understand how its 17..

I don't understand how its 17.. What is the output of this code? int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result);

16th Nov 2016, 7:52 PM
Ella
3 Respostas
+ 1
0 +1+2+10+4
16th Nov 2016, 7:57 PM
Дмитрий Шкурко
0
There's a few things that need to be considered in this for loop. First of all, for the condition, or the middle part of the arguments, you have it set to i < 5, so as long as i is less than 5, the code will run. Then, right after that, you have i++. If you have the ++ after the variable, like you do here, then the ++ will trigger after the variable is used (or in this case, after this loop goes through once more), whereas having the ++ before the i would trigger it to increase by one, and then use the variable in the loop. The first iteration of the loop has i set to 0 because i has not incremented yet, so it finishes as result = 0. In the second iteration, i is now equal to 1, so result is also 1. For the third iteration, i is set to 2, so 1 + 2 means result is equal to 3. For the next iteration of the loop, i is equal to 3, which triggers the if statement to make result = 3 + 10 = 13. For the fifth iteration, i is equal to 4, so result is 13 + 4 = 17. After this iteration, i is now equal to 5. Since the for loop indicates that the for loop runs as long as i is less than 5, and not less than or equal to 5 (indicated by <= instead of just <), the loop is finished.
16th Nov 2016, 8:40 PM
joey
joey - avatar
0
@Дмитрий exactly.
16th Nov 2016, 8:53 PM
Dima Simonishvili
Dima Simonishvili - avatar