Question 341
What is printed?
int n = 9876;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println(sum);Main Solution
The code computes the sum of the digits of n = 9876 by repeatedly extracting the last digit using n % 10 and then removing it with n /= 10.
Trace through the loop:
| Iteration | n | n % 10 | sum |
|---|---|---|---|
| 1 | 9876 | 6 | 0 + 6 = 6 |
| 2 | 987 | 7 | 6 + 7 = 13 |
| 3 | 98 | 8 | 13 + 8 = 21 |
| 4 | 9 | 9 | 21 + 9 = 30 |
| — | 0 | — | loop ends |
After the loop, sum = 30, so System.out.println(sum) prints 30. The correct answer is A.
Teacher Explanation
This question tests understanding of the modulo operator (%) and integer division (/=) as a digit-extraction pattern. Each iteration strips the units digit and accumulates it into sum. Students must correctly trace integer arithmetic: 9876 % 10 = 6, 9876 / 10 = 987, etc., until n reaches 0.
Education Coach Advice
When tracing loops that use % 10 and / 10, build a table with columns for n, n % 10, and sum at each iteration. This prevents arithmetic errors and makes it easy to verify the loop termination condition. On the AP exam, digit-sum and digit-reversal patterns appear frequently — recognize them quickly.
Traps
Option B (24) is the most common trap. Students may mistakenly add only some of the digits (e.g., skip the first or last iteration) or confuse the order of operations inside the loop. Option D (6789) attracts students who think the loop reverses the digits rather than sums them. Option C (9876) attracts students who think println(sum) prints n instead of sum.
Answer images

