Practice a College Board-style Methods and Control Structures free response with conditionals and loops. Write your Java, then reveal the model answer to see exactly what earns each point.
Free Response Question · Unit 2 · Selection and Iteration
Write Java code segments (methods) that use selection and iteration. Assume the parameters are valid. This mirrors the exam’s Methods and Control Structures question.
A
Write a method countMultiples(int n, int d) that returns how many integers from 1 to n (inclusive) are evenly divisible by d.
✓ Model answer
public int countMultiples(int n, int d) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (i % d == 0) {
count++;
}
}
return count;
}
Why it scores: Loops over 1..n inclusive, uses % to test divisibility, increments a counter inside an if, and returns it. Using i < n (off-by-one) or the wrong modulus test would lose points.
B
Write a method countVowels(String s) that returns the number of vowels (a, e, i, o, u, lowercase) in s.
✓ Model answer
public int countVowels(String s) {
int count = 0;
String vowels = "aeiou";
for (int i = 0; i < s.length(); i++) {
if (vowels.indexOf(s.substring(i, i + 1)) >= 0) {
count++;
}
}
return count;
}
Why it scores: Traverses every index 0..length()−1, extracts each character with substring, and tests membership with indexOf (≥ 0 means found). Looping past the last index (using <=) would throw an exception and lose credit.
C
Describe how many times the inner statement runs in a nested loop where the outer loop runs 5 times and the inner loop runs 3 times, and explain your reasoning.
✓ Model answer
The inner statement runs 15 times. For each of the 5 outer iterations, the inner loop completes all 3 of its iterations, so the total is 5 × 3 = 15 (a multiplication, not an addition).
Why it scores: Correctly multiplies the loop counts (5 × 3) and justifies it by noting the inner loop runs fully per outer pass. Answering 8 (adding) would lose the point.
How to score points on AP CSA free response
Match loop bounds to the task — use <= for inclusive ranges, < length() for String traversal.
Initialize accumulators (like count) before the loop and return them after.
Use % for divisibility and .indexOf()/.substring() for String membership.
Nested loop counts multiply — outer × inner.
Answer the verb. "Write a method" wants complete Java; "describe" wants reasoning.