Question 151
int sum = 0;
for (int i = 1; i <= 10; i++)
{
if (i % 3 == 0)
{
i++;
}
sum = sum + i;
}
System.out.println(sum);
What is printed when the code segment executes?Main Solution
Solution:
Answer: D. Inside the body, when i is a multiple of 3, it is incremented before the add, and then the for-update increments it again. Tracing: i = 1 adds 1 (sum = 1); i = 2 adds 2 (3); i = 3 → body bumps to 4, adds 4 (7), then update → 5; adds 5 (12); i = 6 → bumps to 7, adds 7 (19), update → 8; adds 8 (27); i = 9 → bumps to 10, adds 10 (37), update → 11; 11 <= 10 is false, exit. Sum is 37.
Answer: Correct: D
Answer images

