Question 171
What is printed?
int result = 1;
for (int i = 1; i <= 5; i++) {
if (i % 2 == 1) {
result *= i;
} else {
result += i;
}
}
System.out.println(result);Main Solution
We trace through the loop step by step, tracking result:
| i | i % 2 == 1? | Operation | result (after) |
|---|---|---|---|
| — | — | Initial | 1 |
| 1 | Yes (1 % 2 = 1) | result *= 1 → 1 × 1 | 1 |
| 2 | No (2 % 2 = 0) | result += 2 → 1 + 2 | 3 |
| 3 | Yes (3 % 2 = 1) | result *= 3 → 3 × 3 | 9 |
| 4 | No (4 % 2 = 0) | result += 4 → 9 + 4 | 13 |
| 5 | Yes (5 % 2 = 1) | result *= 5 → 13 × 5 | 65 |
After the loop completes, System.out.println(result) prints 65. The correct answer is D.
Teacher Explanation
This question tests students' ability to trace a loop that alternates between multiplication (for odd i) and addition (for even i). The key insight is that i % 2 == 1 is true for odd values of i (1, 3, 5) and false for even values (2, 4). Students must carefully apply the correct operation at each iteration and carry the running value of result forward.
Education Coach Advice
AP Exam Strategy: For loop-tracing questions, always create a table with columns for the loop variable, the condition result, the operation performed, and the updated variable value. Work through each iteration methodically — do not try to shortcut the trace. Pay special attention to the initial value of variables before the loop begins (here, result = 1, not 0), as this affects multiplication results significantly.
Traps
Common traps:
- Option A (15): Students may multiply all values 1×2×3×4×5 = 120, then make arithmetic errors, or only multiply the odd numbers 1×3×5 = 15, ignoring the addition steps for even numbers.
- Option B (25): Students may add all values 1+2+3+4+5 = 15 and then make an error, or confuse which branch applies to which iteration.
- Option C (45): Students may correctly handle some iterations but make an arithmetic mistake, e.g., computing 9 + 4 = 13 incorrectly as 9 + 4 = 9, then 9 × 5 = 45.
Answer images

