Question 171
What is printed?
int sum = 0;
for (int i = 1; i <= 30; i++) {
if (i % 3 == 0 && i % 2 != 0) {
sum += i;
}
}
System.out.println(sum);Answer images
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
What is printed?
int sum = 0;
for (int i = 1; i <= 30; i++) {
if (i % 3 == 0 && i % 2 != 0) {
sum += i;
}
}
System.out.println(sum);
What is printed?
int sum = 0;
for (int i = 1; i <= 4; i++) {
for (int j = i; j <= 4; j++) {
sum += j;
}
}
System.out.println(sum);We trace through the nested loops carefully.
The outer loop runs for i = 1, 2, 3, 4. For each value of i, the inner loop runs for j = i, i+1, ..., 4, adding each j to sum.
| i | j values | sum added |
|---|---|---|
| 1 | 1, 2, 3, 4 | 1+2+3+4 = 10 |
| 2 | 2, 3, 4 | 2+3+4 = 9 |
| 3 | 3, 4 | 3+4 = 7 |
| 4 | 4 | 4 |
Total: \(10 + 9 + 7 + 4 = 30\)
Therefore, System.out.println(sum) prints 30, which is answer A.
This question tests students' ability to trace nested loops where the inner loop's starting index depends on the outer loop variable. The key insight is that j starts at i (not at 1 or 0), so the inner loop runs fewer iterations as i increases. Students must carefully accumulate the sum for each combination of i and j.
When tracing nested loops on the AP exam, create a table with columns for each loop variable and track the running total step by step. Pay special attention to the inner loop's initialization — here j = i means the inner loop shrinks as i grows. Writing out each iteration systematically prevents arithmetic mistakes.
Option B (20): A student might only sum the values of j for i = 1 (getting 10) and double it, or miscalculate by forgetting that j starts at i rather than 1. Option C (40): A student might assume the inner loop always runs from 1 to 4 for every i, giving \(4 \times 10 = 40\). Option D (26): A student might make an arithmetic error when summing the partial sums.
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);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.
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.
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.
Common traps:
What is printed?
int n = 9876;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println(sum);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.
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.
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.
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.
What is printed?
String s = "MISSISSIPPI";
int count = 0;
int pos = s.indexOf("SS");
while (pos != -1) {
count++;
s = s.substring(pos + 2);
pos = s.indexOf("SS");
}
System.out.println(count + " " + s.length());Let's trace through the code step by step.
Initial state:
s = "MISSISSIPPI"count = 0pos = s.indexOf("SS") → "MISSISSIPPI": first occurrence of "SS" is at index 2 (M-I-S-S...), so pos = 2.Iteration 1: pos = 2 ≠ -1, so enter loop.
count++ → count = 1s = s.substring(pos + 2) = s.substring(4) → "MISSISSIPPI".substring(4) = "ISSIPPI"pos = s.indexOf("SS") on "ISSIPPI": I-S-S → index 1, so pos = 1.Iteration 2: pos = 1 ≠ -1, so enter loop.
count++ → count = 2s = s.substring(pos + 2) = s.substring(3) → "ISSIPPI".substring(3) = "IPPI"pos = s.indexOf("SS") on "IPPI": no "SS" found → pos = -1.Loop exits.
Output: System.out.println(count + " " + s.length()) → count = 2, s = "IPPI", s.length() = 4 → prints 2 4.
The correct answer is B.
This question tests students' understanding of String.indexOf() and String.substring() in a loop. The key insight is that s is being reassigned each iteration (starting from pos + 2), so the search continues on the shortened string. Students must carefully track the changing value of s and the resulting index positions across iterations.
When tracing string manipulation loops on the AP exam, always write out the value of every variable after each line. Pay special attention to when a variable like s is reassigned — the new value feeds into the next iteration. Use a small table with columns for s, count, and pos to avoid losing track.
Common traps:
s is being shortened each iteration and instead compute s.length() on the original or a longer string."SS" occurrences in the original string "MISSISSIPPI" (which has 3: at indices 2, 5, and... wait, actually only 2 non-overlapping from left), or misapply the substring logic to find a third match.substring(pos + 2) vs substring(pos + 1) would yield a different remaining string length.
What is printed?
int a = 100, b = 73;
int count = 0;
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
count++;
}
System.out.println(a + " " + count);This code implements the Euclidean algorithm for finding the GCD of a = 100 and b = 73, counting iterations.
Let's trace through the loop:
| Iteration | a | b | count |
|---|---|---|---|
| Start | 100 | 73 | 0 |
| 1 | 27 | 73 | 1 |
| 2 | 27 | 46 | 2 |
| 3 | 27 | 19 | 3 |
| 4 | 8 | 19 | 4 |
| 5 | 8 | 11 | 5 |
| 6 | 8 | 3 | 6 |
| 7 | 5 | 3 | 7 |
| 8 | 2 | 3 | 8 |
| 9 | 2 | 1 | 9 |
| 10 | 1 | 1 | 10 |
After iteration 10, a == b == 1, so the while condition a != b is false and the loop exits. System.out.println(a + " " + count) prints 1 10.
The correct answer is A.
This is a simulation of the subtraction-based Euclidean GCD algorithm. Students must carefully trace 10 iterations. The GCD of 100 and 73 is 1 (they are coprime), so the algorithm terminates with both variables equal to 1. The count of iterations is 10, giving output 1 10.
For loop-tracing questions, create a table with one row per iteration tracking all variables. Don't try to do it mentally — write it out. Also note that this is the subtraction-based GCD algorithm; recognizing it can help you verify your answer (GCD(100,73) = 1).
Option D (1 7) is a common trap — students may miscount iterations or stop early. Option B (1 8) and Option C (27 3) reflect stopping the trace too early (e.g., after only 3 subtractions or miscounting when a first becomes 27). Careful step-by-step tracing is essential to avoid these errors.
What is printed?
String s = "ABCDE";
String result = "";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
result = result + s.substring(j, j + 1);
}
}
System.out.println(result.length() + " " + result.substring(result.length() - 5));Step 1: Trace the nested loops to build result.
s = "ABCDE" (indices 0–4). The outer loop runs for i = 0, 1, 2, 3, 4. The inner loop runs j from 0 to i (inclusive), appending s.substring(j, j+1) each time.
| i | j values | Characters appended |
|---|---|---|
| 0 | 0 | A |
| 1 | 0, 1 | A, B |
| 2 | 0, 1, 2 | A, B, C |
| 3 | 0, 1, 2, 3 | A, B, C, D |
| 4 | 0, 1, 2, 3, 4 | A, B, C, D, E |
So result = "A" + "AB" + "ABC" + "ABCD" + "ABCDE" = "AABABCABCDABCDE"
Step 2: Compute result.length().
Lengths: 1 + 2 + 3 + 4 + 5 = 15.
Step 3: Compute result.substring(result.length() - 5) = result.substring(10).
result = "AABABCABCDABCDE"
Characters at indices 10–14: A, B, C, D, E → "ABCDE".
Step 4: Output.
System.out.println(15 + " " + "ABCDE") prints: 15 ABCDE.
The correct answer is C.
The key insight is understanding how the nested loop builds result: for each value of i, the inner loop appends characters from index 0 up to index i. This produces the concatenation "A" + "AB" + "ABC" + "ABCD" + "ABCDE", giving a 15-character string ending in "ABCDE". Students must carefully trace both the length (1+2+3+4+5=15) and the last 5 characters of the resulting string.
When tracing nested loops that build strings, write out each iteration's contribution explicitly in a table. Then concatenate them in order. For substring(length - n), count carefully from the end of the fully built string. Don't try to shortcut — one missed character changes the answer entirely.
Option A (15 BCDE): A student might mistakenly think the inner loop starts at j = 1 instead of j = 0, skipping 'A' in each iteration — but the loop condition is j = 0.
Option B (10 ABCDE): A student might count only unique characters appended or miscalculate the total length as 10 (perhaps thinking the loop runs only 4 times for i=0..3).
Option D (15 EABCD): A student might confuse the order of characters in the last 5 positions, perhaps thinking the last character appended is 'E' followed by the previous iteration's output — but the string ends with the full "ABCDE" from the i=4 iteration.
What is printed?
String s = "ABCDEF";
String result = "";
for (int i = 0; i < s.length(); i += 2) {
result = s.substring(i, i + 1) + result;
}
System.out.println(result);Let's trace through the code step by step.
s = "ABCDEF" (indices 0–5), result = ""
The loop runs with i += 2, so i takes values 0, 2, 4.
s.substring(0, 1) = "A". result = "A" + "" = "A"s.substring(2, 3) = "C". result = "C" + "A" = "CA"s.substring(4, 5) = "E". result = "E" + "CA" = "ECA"6 < 6 is false, loop ends.System.out.println(result) prints ECA.
The correct answer is D.
The key insight is that each iteration prepends (not appends) the character to result via result = s.substring(i, i+1) + result. The loop visits every other character (A at index 0, C at index 2, E at index 4), but because each new character is placed at the front, the final string is the reverse order of those characters: ECA.
Whenever you see string concatenation inside a loop, pay close attention to the order of operands: newChar + result prepends (builds in reverse), while result + newChar appends (builds in forward order). Trace through 2–3 iterations on your scratch paper to confirm the direction before choosing your answer.
Option A (ACE) is the most common trap: students correctly identify that the loop picks characters at indices 0, 2, 4 (A, C, E) but forget that the concatenation is s.substring(i, i+1) + result, which prepends each new character, reversing the order. Option C (FEDCBA) would result if all characters were reversed, not just the even-indexed ones.
What is printed?
int total = 0;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
total += i;
}
}
System.out.println(total);The code sums all integers from 1 to 100 that are divisible by both 3 and 5 (i.e., divisible by 15).
A number divisible by both 3 and 5 must be divisible by their LCM, which is 15. The multiples of 15 from 1 to 100 are:
15, 30, 45, 60, 75, 90
Sum = 15 + 30 + 45 + 60 + 75 + 90
= (15 + 90) + (30 + 75) + (45 + 60)
= 105 + 105 + 105
= 315
Therefore, System.out.println(total) prints 315, which is answer choice B.
This question tests students' understanding of compound boolean conditions using && (logical AND) and the modulo operator %. The condition i % 3 == 0 && i % 5 == 0 is true only when i is divisible by both 3 and 5, which means divisible by 15. Students must correctly identify all multiples of 15 up to 100 and sum them.
When you see i % a == 0 && i % b == 0, immediately recognize this as divisibility by LCM(a, b). List out the multiples systematically and add them carefully. Double-check the loop bounds — here i <= 100 means 100 is included, but 105 is not. Pair up numbers to add quickly: (15+90), (30+75), (45+60) = 105 × 3 = 315.
Common traps:
What is printed?
int count = 0;
for (int i = 1; i <= 20; i++) {
boolean divisible = false;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
divisible = true;
}
}
if (!divisible && i > 1) {
count++;
}
}
System.out.println(count);This code counts the number of prime numbers from 2 to 20 (inclusive).
For each value of i from 1 to 20, the inner loop checks whether i has any divisor j in the range [2, √i]. If it does, divisible is set to true. After the inner loop, if !divisible && i > 1, then i is prime and count is incremented.
The primes from 2 to 20 are:
That gives us 8 primes: {2, 3, 5, 7, 11, 13, 17, 19}.
Therefore, count = 8 and the program prints 8.
This is a classic primality-testing algorithm using trial division up to √i. The condition j * j <= i is equivalent to j <= Math.sqrt(i). The condition i > 1 excludes 1 (which is not prime). Students should recognize this as a prime-counting loop and enumerate the primes from 2 to 20: there are exactly 8 of them.
When you see a nested loop with a condition like j * j <= i and a divisibility check, immediately recognize it as a primality test. Quickly list the primes up to the loop bound (here 20): 2, 3, 5, 7, 11, 13, 17, 19 — that's 8. Don't forget to check edge cases like i=1 (excluded by i > 1) and i=2 (inner loop never runs, so it's correctly counted as prime).
Common traps:
j * j <= i means the inner loop never executes for i=2 (since 2×2=4 > 2). They might incorrectly think 2 is not handled.i > 1 guard.
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.