+ 1

Why is the answer 17?

int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result); Can someone please explain to me why the answer is 17?

14th Jan 2023, 2:16 AM
Gradi Maxime Kasita Mbatika
3 Answers
+ 1
Because the loop run through the i values as: 0-1-2-3-4 Every i loop value will added to the result variable because of the += operator. And when the i value is equal to 3 the result value will be added with 10 not 3 So the calculation would be as 0 + 0 + 1 + 2 + 10 + 4 The sum is equal to 17 Great!😊💐
14th Jan 2023, 3:48 AM
Ab SH
+ 1
Thank you Ab SH! 👍
14th Jan 2023, 4:59 AM
Gradi Maxime Kasita Mbatika
0
You are welcome đŸŒŒ
14th Jan 2023, 5:02 AM
Ab SH