Question 291
What is printed?
int n = 2;
int count = 0;
while (n < 1000) {
n = n * n;
count++;
}
System.out.println(n + " " + count);Main Solution
Let's trace through the code step by step:
- Initial values:
n = 2,count = 0 - Iteration 1: Is
2 < 1000? Yes.n = 2 * 2 = 4,count = 1 - Iteration 2: Is
4 < 1000? Yes.n = 4 * 4 = 16,count = 2 - Iteration 3: Is
16 < 1000? Yes.n = 16 * 16 = 256,count = 3 - Iteration 4: Is
256 < 1000? Yes.n = 256 * 256 = 65536,count = 4 - Check: Is
65536 < 1000? No. Exit loop.
After the loop, System.out.println(n + " " + count) prints 65536 4.
The correct answer is D.
Teacher Explanation
This question tests students' ability to trace a while loop where the loop variable grows very rapidly (squaring each iteration). Students must carefully track both n and count through each iteration. The loop runs exactly 4 times before n exceeds 1000, ending at 65536. The key insight is that the loop body executes when n < 1000, so the final squaring (256 → 65536) still occurs inside the loop on the 4th iteration.
Education Coach Advice
When tracing loops on the AP exam, create a table with columns for each variable and update them row by row. Always check the loop condition before executing the body. For this problem: track n and count together each iteration. Remember that count++ happens inside the loop, so count only increments when the body executes — not when the condition fails.
Traps
Common traps:
- Option A (256 3): Students may think the loop exits when
n = 256because 256 is close to 1000, but 256 < 1000 is still true, so the loop runs one more time. - Option B (16 2): Students may incorrectly stop the loop at
n = 16, perhaps misreading the condition or miscounting iterations. - Option C (65536 5): Students may count 5 iterations by mistakenly counting the failed loop check as an iteration, or by starting count at 1 instead of 0.
Answer images

