AP® Computer Science A Selection and Iteration Practice Questions
Work through AP Computer Science A practice questions on Selection and Iteration, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Subtopic: Iteration Clear filter
Question 162
What is printed?
int product = 1;
for (int i = 1; i <= 6; i++) {
if (i % 2 == 0) {
product *= i;
}
}
System.out.println(product);Main Solution
The code initializes product = 1 and loops i from 1 to 6 (inclusive). Inside the loop, it multiplies product by i only when i % 2 == 0, i.e., only for even values of i.
The even values in the range [1, 6] are: 2, 4, 6.
Step-by-step:
i = 1: 1 % 2 = 1 ≠ 0 → skipi = 2: 2 % 2 = 0 → product = 1 × 2 = 2i = 3: 3 % 2 = 1 ≠ 0 → skipi = 4: 4 % 2 = 0 → product = 2 × 4 = 8i = 5: 5 % 2 = 1 ≠ 0 → skipi = 6: 6 % 2 = 0 → product = 8 × 6 = 48
So System.out.println(product) prints 48. The correct answer is A.
Teacher Explanation
This question tests students' ability to trace a loop with a conditional. The key insight is that only even values of i (2, 4, 6) contribute to the product. The product of the even integers from 2 to 6 is 2 × 4 × 6 = 48.
Education Coach Advice
When tracing loops on the AP exam, create a small table tracking the loop variable and any accumulator variable at each iteration. Pay close attention to the loop condition (i <= 6 vs i < 6) and any inner conditionals. This prevents off-by-one errors and missed conditions.
Traps
Option C (24) is a common trap: students may mistakenly compute 2 × 3 × 4 = 24, confusing which values pass the even check, or stopping the loop early. Option D (720) is 6! (factorial of 6), which would be the result if the condition were removed entirely and all values 1–6 were multiplied. Option B (36) might result from multiplying 6 × 6 or some other miscount.
Answer images
Question 163
What is printed?
int sum = 0;
for (int i = 1; i <= 4; i++) {
for (int j = i; j <= 4; j++) {
sum += i * j;
}
}
System.out.println(sum);Main Solution
We need to trace the nested loops and accumulate sum.
The outer loop runs i from 1 to 4. The inner loop runs j from i to 4. Each iteration adds i * j to sum.
| i | j | i * j |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 1 | 3 | 3 |
| 1 | 4 | 4 |
| 2 | 2 | 4 |
| 2 | 3 | 6 |
| 2 | 4 | 8 |
| 3 | 3 | 9 |
| 3 | 4 | 12 |
| 4 | 4 | 16 |
Sum = 1 + 2 + 3 + 4 + 4 + 6 + 8 + 9 + 12 + 16 = 65
Therefore, System.out.println(sum) prints 65, which is answer C.
Teacher Explanation
The key detail is that the inner loop starts at j = i, not j = 1. This means the pairs (i, j) only cover the upper triangle of the multiplication table (where j ≥ i). Students must carefully trace the starting condition of the inner loop. The total of all products in this triangular region is 65.
Education Coach Advice
When tracing nested loops on the AP exam, always note the starting condition of the inner loop — here j = i is the critical detail. Create a small table tracking i, j, and the running sum. This systematic approach prevents arithmetic errors and ensures you don't miss any iterations.
Traps
Option B (55) is a common trap: 55 is the sum of all integers from 1 to 10, which students might arrive at if they confuse this with a simple summation loop. Option A (60) might result from starting the inner loop at j = 1 but only summing i + j instead of i * j. Option D (70) could result from starting the inner loop at j = 1 instead of j = i, computing the full upper-left triangle including the diagonal twice.
Answer images
Question 164
What is printed?
String s = "aAbBcCdD";
String result = "";
for (int i = 0; i < s.length(); i++) {
String ch = s.substring(i, i + 1);
if (ch.compareTo("a") >= 0 && ch.compareTo("z") <= 0) {
result += ch;
}
}
System.out.println(result);Main Solution
The code iterates over each character of the string "aAbBcCdD" and checks whether each single-character substring ch satisfies:
ch.compareTo("a") >= 0 && ch.compareTo("z") <= 0This condition is true only for lowercase letters (characters whose Unicode/ASCII values fall between 'a' (97) and 'z' (122) inclusive).
Let's trace through each character of "aAbBcCdD":
| Index | ch | compareTo("a") >= 0 | compareTo("z") <= 0 | Added? |
|---|---|---|---|---|
| 0 | a | 0 >= 0 ✓ | -25 <= 0 ✓ | Yes |
| 1 | A | -32 >= 0 ✗ | — | No |
| 2 | b | 1 >= 0 ✓ | -24 <= 0 ✓ | Yes |
| 3 | B | -31 >= 0 ✗ | — | No |
| 4 | c | 2 >= 0 ✓ | -23 <= 0 ✓ | Yes |
| 5 | C | -30 >= 0 ✗ | — | No |
| 6 | d | 3 >= 0 ✓ | -22 <= 0 ✓ | Yes |
| 7 | D | -29 >= 0 ✗ | — | No |
Only the lowercase letters a, b, c, d are appended to result, so System.out.println(result) prints abcd.
The correct answer is C.
Teacher Explanation
This question tests students' understanding of String.compareTo() and Unicode/ASCII ordering. Uppercase letters ('A'–'Z') have ASCII values 65–90, which are less than 'a' (97), so ch.compareTo("a") returns a negative number for uppercase letters, failing the >= 0 check. Only lowercase letters pass both conditions and get appended to result.
Education Coach Advice
When you see compareTo() on single characters, remember that Java uses Unicode (ASCII) ordering: uppercase letters (65–90) come before lowercase letters (97–122). So "A".compareTo("a") returns a negative number. Trace through a few characters manually to confirm which pass the condition before selecting your answer.
Traps
Option A (ABCD): A student might mistakenly think the condition filters for uppercase letters, reversing the compareTo logic. Option B (aAbBcCdD): A student might think all characters pass the condition, not realizing uppercase letters fail compareTo("a") >= 0. Option D (AbCd): A student might confuse which letters are uppercase vs. lowercase in the original string or misread the alternating pattern.
Answer images
Question 165
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
Question 166
What is printed?
int n = 4821;
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n = n / 10;
}
System.out.println(reversed);Main Solution
We trace through the code step by step, starting with n = 4821 and reversed = 0.
| Iteration | n (before) | reversed = reversed * 10 + n % 10 | n = n / 10 |
|---|---|---|---|
| 1 | 4821 | 0 * 10 + 4821 % 10 = 0 + 1 = 1 | 4821 / 10 = 482 |
| 2 | 482 | 1 * 10 + 482 % 10 = 10 + 2 = 12 | 482 / 10 = 48 |
| 3 | 48 | 12 * 10 + 48 % 10 = 120 + 8 = 128 | 48 / 10 = 4 |
| 4 | 4 | 128 * 10 + 4 % 10 = 1280 + 4 = 1284 | 4 / 10 = 0 |
After iteration 4, n = 0, so the while loop exits. System.out.println(reversed) prints 1284, which is the digits of 4821 reversed.
The correct answer is D) 1284.
Teacher Explanation
This question tests students' ability to trace a digit-extraction algorithm. The pattern n % 10 extracts the last digit, and n / 10 removes it (integer division). Multiplying reversed by 10 each iteration shifts previously collected digits left, effectively building the reversed number. Students must carefully trace each iteration to arrive at 1284.
Education Coach Advice
When tracing loops on the AP exam, create a table with columns for each variable and update them one iteration at a time. For digit-manipulation problems, remember: n % 10 gives the last digit, and n / 10 (integer division) removes it. Work slowly and check your arithmetic at each step — one small error will lead you to a wrong answer choice.
Traps
Option A (4821): A student might think the code simply prints n unchanged, ignoring the loop logic entirely.
Option B (1482): A student might confuse the order of operations or think the algorithm rotates rather than reverses digits.
Option C (4218): A student might incorrectly apply the modulo/division operations, perhaps reversing only part of the number or making an arithmetic error mid-trace.
The most common trap is making an arithmetic error during the trace, especially in iteration 3 or 4 where the numbers get larger.
Answer images
Question 167
What is printed?
int total = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i + j == 6) {
total += i * j;
}
}
}
System.out.println(total);Main Solution
We need to find all pairs (i, j) where both i and j range from 1 to 5 and i + j == 6, then sum up i * j for each such pair.
The pairs (i, j) satisfying i + j = 6 with 1 ≤ i ≤ 5 and 1 ≤ j ≤ 5 are:
| i | j | i * j |
|---|---|---|
| 1 | 5 | 5 |
| 2 | 4 | 8 |
| 3 | 3 | 9 |
| 4 | 2 | 8 |
| 5 | 1 | 5 |
Summing the products: 5 + 8 + 9 + 8 + 5 = 35.
Therefore, System.out.println(total) prints 35, which is answer choice A.
Teacher Explanation
This question tests students' ability to trace nested loops with a conditional. The key insight is identifying which (i, j) pairs satisfy i + j == 6 within the given ranges, then computing and accumulating i * j. There are exactly 5 such pairs, and their products sum to 35.
Education Coach Advice
When tracing nested loops on the AP exam, create a small table tracking the loop variables and any accumulator. For each iteration, check the condition and update the accumulator. This systematic approach prevents arithmetic errors and ensures no valid pair is missed. Pay close attention to loop bounds (<= vs <) and the exact condition (== 6 here).
Traps
Option B (30) is the most common trap: students may forget one of the pairs (e.g., skip (1,5) or (5,1)) or miscalculate a product. Option C (25) might result from only counting pairs where i < j (i.e., only (1,5) and (2,4) and (3,3)), giving 5 + 8 + 9 = 22 — or from other off-by-one errors. Option D (40) could arise from incorrectly including pairs outside the valid range or double-counting.
Answer images
Question 168
What is printed?
String s = "ABCDEFGHIJ";
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
if (i % 3 == 0) {
result += s.substring(i, i + 1);
}
}
System.out.println(result);Main Solution
Let's trace through the code step by step.
s = "ABCDEFGHIJ" has indices 0–9:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Char | A | B | C | D | E | F | G | H | I | J |
s.length() is 10, so i starts at 9 and counts down to 0.
The condition is i % 3 == 0, so we include characters at indices where i is divisible by 3:
- i = 9: 9 % 3 == 0 ✓ →
s.substring(9, 10)= J - i = 8: 8 % 3 = 2 ✗
- i = 7: 7 % 3 = 1 ✗
- i = 6: 6 % 3 == 0 ✓ →
s.substring(6, 7)= G - i = 5: 5 % 3 = 2 ✗
- i = 4: 4 % 3 = 1 ✗
- i = 3: 3 % 3 == 0 ✓ →
s.substring(3, 4)= D - i = 2: 2 % 3 = 2 ✗
- i = 1: 1 % 3 = 1 ✗
- i = 0: 0 % 3 == 0 ✓ →
s.substring(0, 1)= A
Since the loop runs from high to low and appends each character, result = "JGDA".
The correct answer is C: JGDA.
Teacher Explanation
This question tests students' understanding of: (1) iterating a loop in reverse order, (2) the modulo operator to select indices divisible by 3, and (3) string concatenation building the result in reverse order. The key insight is that the loop goes from index 9 down to 0, so characters are appended in reverse index order, giving JGDA rather than ADGJ.
Education Coach Advice
When tracing string-building loops on the AP exam: (1) Write out the index-to-character mapping first. (2) Note the loop direction (i++ vs i--). (3) List only the indices that satisfy the condition, in the order the loop visits them. (4) Concatenate in that order. This systematic approach prevents the common mistake of getting the right characters but in the wrong order.
Traps
Option A (ADGJ) is the most common trap. Students who correctly identify that indices 0, 3, 6, 9 are divisible by 3 (giving A, D, G, J) but forget that the loop iterates in descending order will reverse the order of concatenation and choose ADGJ. Always trace the loop direction carefully — because i-- decrements, characters are appended starting from index 9 down to 0, producing JGDA.
Option D (JHDA) may attract students who mistakenly think index 9 maps to 'J' and index 7 maps to 'H', confusing which indices satisfy i % 3 == 0.
Answer images
Question 169
Consider the following method.
public static int classify(int n) {
int sumDiv = 0;
for (int i = 1; i < n; i++) {
if (n % i == 0)
sumDiv += i;
}
if (sumDiv == n) return 0;
if (sumDiv > n) return 1;
return -1;
}
What is the return value of classify(28) ?
Main Solution
To determine the return value of classify(28), we need to find all proper divisors of 28 (i.e., all integers i where 1 ≤ i < 28 and 28 % i == 0), then sum them.
The divisors of 28 that are less than 28 are: 1, 2, 4, 7, 14.
Sum: \(1 + 2 + 4 + 7 + 14 = 28\)
So sumDiv = 28, which equals n = 28.
The condition if (sumDiv == n) is true, so the method returns 0.
The correct answer is A.
Note: 28 is a perfect number — a number equal to the sum of its proper divisors. The method essentially classifies numbers: 0 for perfect, 1 for abundant (sum > n), and -1 for deficient (sum < n).
Teacher Explanation
This question tests students' ability to trace through a loop and accumulate a sum. The key insight is recognizing that the loop iterates i from 1 up to (but not including) n, adding i to sumDiv whenever i is a divisor of n. For n = 28, the proper divisors are 1, 2, 4, 7, 14, which sum to 28 — making 28 a perfect number and causing the method to return 0.
Education Coach Advice
AP Exam Strategy: When tracing loops, carefully check the loop bounds — here i < n (strict inequality) means n itself is never tested as a divisor. List out all divisors systematically and sum them before evaluating the conditionals. For number-theory style problems, recall that perfect numbers (like 6, 28, 496) equal the sum of their proper divisors.
Traps
Common traps:
- Option B (1): Students might mistakenly include 28 itself as a divisor (since
28 % 28 == 0), giving a sum of 56 > 28, and incorrectly returning 1. However, the loop condition isi < n, soi = 28is never tested. - Option C (-1): Students might miscalculate the sum of divisors and get a value less than 28, returning -1.
- Option D (28): Students might confuse the return value with the input value.
Answer images
Question 170
What is printed?
int a = 48, b = 18;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
System.out.println(a);Main Solution
This code implements the Euclidean algorithm for finding the Greatest Common Divisor (GCD) of two numbers. Let's trace through the execution with a = 48 and b = 18:
| Iteration | a (before) | b (before) | temp | b = a % b | a = temp |
|---|---|---|---|---|---|
| 1 | 48 | 18 | 18 | 48 % 18 = 12 | 18 |
| 2 | 18 | 12 | 12 | 18 % 12 = 6 | 12 |
| 3 | 12 | 6 | 6 | 12 % 6 = 0 | 6 |
| 4 | 6 | 0 | Loop exits (b == 0) | ||
After the loop, a = 6, so System.out.println(a) prints 6.
Indeed, GCD(48, 18) = 6, since 48 = 6 × 8 and 18 = 6 × 3.
The correct answer is B) 6.
Teacher Explanation
This question tests students' ability to trace through a while loop that implements the Euclidean GCD algorithm. Students must carefully track how a and b change each iteration using the temporary variable temp. The loop terminates when b becomes 0, at which point a holds the GCD. Key skills: loop tracing, modulo operator, and temporary variable swap pattern.
Education Coach Advice
AP Exam Strategy: When tracing loops, create a table with columns for each variable and fill in values after each iteration. Pay special attention to the order of assignments — here, temp saves b before b is overwritten, then a gets the old b. Always check the loop condition after each iteration to know when to stop. Recognize the Euclidean GCD pattern: it's a common algorithm tested on the AP CSA exam.
Traps
Common traps:
- Option D (18): Students may think the answer is the initial value of
bor confuse which variable is printed. They might also stop tracing after the first iteration. - Option C (12): Students who stop tracing after the second iteration (when
abecomes 12) will choose this. - Option A (1): Students may confuse GCD with 1 (thinking all numbers share a GCD of 1) or make an arithmetic error with the modulo operator.
Answer images
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

