Consider the following code segment. What is printed as a result of executing the code segment?
int sum = 0;
for (int value = 2; value <= 8; value += 2) {
if (value > 4) {
sum += value;
}
}
System.out.println(sum);
81214202, 4, 6, and 8, and only 6 and 8 pass the test, giving 14.
Explanation
This combines selection with the accumulator pattern. The accumulator sum starts at 0 and is updated only when the current value qualifies. The guard value > 4 rejects 2 and 4, so the running total collects the two larger values.
- A is not correct: only
8is included by this answer, but6also satisfiesvalue > 4and must join the running total. - B is not correct: adding
2,4, and6gives12, but the condition rejects2and4while8still qualifies. - D is not correct:
20is the total of every value the loop visits, which ignores theifstatement and includes2and4.