AP CSA Unit 2.7: While Loop Tracing and Accumulator Pattern Practice
Share
Unit 2, Section 2.7
Day 7 Practice • January 13, 2026
🎯 Focus: While Loops
Practice Question
Consider the following code segment:
int sum = 0;
int i = 1;
while (i <= 4) {
sum += i;
i++;
}
System.out.println(sum);
What is printed as a result of executing this code segment?
What This Tests: Section 2.7 covers while loops. This question tests the accumulator pattern—using a variable (sum) to collect values across loop iterations. Trace each iteration carefully!
Step-by-Step Trace
| Iteration | i <= 4? | sum += i | i++ | sum | i |
|---|---|---|---|---|---|
| Before | - | - | - | 0 | 1 |
| 1 | 1 <= 4 ✓ | 0 + 1 | 1 → 2 | 1 | 2 |
| 2 | 2 <= 4 ✓ | 1 + 2 | 2 → 3 | 3 | 3 |
| 3 | 3 <= 4 ✓ | 3 + 3 | 3 → 4 | 6 | 4 |
| 4 | 4 <= 4 ✓ | 6 + 4 | 4 → 5 | 10 | 5 |
| 5 | 5 <= 4 ✗ | - | - | 10 | 5 |
Output: 10 (which is 1 + 2 + 3 + 4)
The Accumulator Pattern
// Accumulator Pattern Structure
int accumulator = 0; // 1. Initialize
while (condition) {
accumulator += value; // 2. Accumulate
// update loop variable // 3. Progress toward exit
}
Common Mistakes
Mistake: Answer A (4)
This confuses the final value of i with the sum. The loop runs 4 times, but sum accumulates 1+2+3+4 = 10.
Mistake: Answer D (15)
This might come from including 5 in the sum (1+2+3+4+5=15). But i <= 4 stops at 4, not 5.
Practice Technique
Loop Tracing Table
Always create a table with columns for:
- The condition check
- Each variable that changes
- Track values BEFORE and AFTER each iteration
Difficulty: Medium • Time: 3-4 minutes • AP Skill: 2.B - Determine code results
Completed Unit 2 Week 1! 🎉
Great job finishing all 7 days of selection and iteration!
Premium Question Bank - Coming Soon Schedule 1-on-1 Tutoring