AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/2/2-9)
Unit 2 · Topic 2.9
2.9 Implementing Selection and Iteration Algorithms
A handful of loop patterns show up again and again: checking divisibility, pulling digits out of a number, counting, finding a minimum or maximum, and computing a sum or average. This topic gives you each pattern so you can adapt it quickly, especially on free-response Question 1.
Key terms
- divisibility with
% - digit extraction
- counter
- minimum and maximum
- sum and average
Divisibility
An integer n divides evenly by d exactly when the remainder is 0: n % d == 0. So n % 2 == 0 tests for even numbers, and n % 2 != 0 tests for odd ones. Likewise, year % 4 == 0 asks whether a year is a multiple of 4. (The course uses % only with a non-negative left side and a positive right side.)
Digits of an integer
For a non-negative integer, num % 10 is its last digit and num / 10 drops that digit. Repeat the two in a loop and you visit every digit, from right to left, until num reaches 0:
int num = 4829;
while (num > 0)
{
System.out.print(num % 10 + " ");
num = num / 10;
}
System.out.println();
With 4829 this prints 9 2 8 4 . The same loop can count digits, add them up, or find the largest one. One edge case: if num starts at 0, the loop runs zero times.
Counting, sum and average
These three patterns share a shape: a variable declared before the loop, updated inside it, and used after it. To count how often something happens, start a counter at 0 and add 1 each time the condition is met. To total values, start a sum at 0 and add each value. An average is the sum divided by the count.
Watch the types. If sum and count are both int, then sum / count is integer division and drops the decimal part. Cast first: (double) sum / count. And make sure count isn't 0 before you divide.
Minimum and maximum
To find the largest value, keep a variable holding the biggest value seen so far. Compare each new value with it and replace it when the new one is bigger. The minimum works the same way with <.
Start that variable at a real value from the data, such as the first one, not at 0. If every value is negative, a maximum that starts at 0 would wrongly stay 0. You can also start at Integer.MIN_VALUE for a maximum or Integer.MAX_VALUE for a minimum, since every int is at least as big as the first and no bigger than the second.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Write a method: counting multiples
Write a method
countMultiples(int low, int high, int d)that returns how many integers fromlowtohigh, inclusive, are divisible byd. Assumedis positive. For example,countMultiples(10, 30, 7)returns 3, for 14, 21 and 28. A full solution:public static int countMultiples(int low, int high, int d) { int count = 0; for (int n = low; n <= high; n++) { if (n % d == 0) { count++; } } return count; }Show the solutionHide the solution
- Step 1: This is the counting pattern: a counter that starts at 0, a loop over every value, and an
ifthat adds 1 when the condition holds. - Step 2: "Inclusive" means
highmust be checked too, so the condition isn <= high, notn < high. - Step 3: The condition is divisibility:
n % d == 0. - Step 4: Return the count after the loop ends, not inside it.
- Step 5: Check: from 10 to 30, the multiples of 7 are 14, 21 and 28, so the method returns 3.
Answer: The method above;
countMultiples(10, 30, 7)returns3. - Step 1: This is the counting pattern: a counter that starts at 0, a loop over every value, and an
- Example 2
Write a method: largest digit
Write a method
largestDigit(int num)that returns the largest digit in a non-negative integer. For example,largestDigit(4829)returns 9. One solution:public static int largestDigit(int num) { int largest = num % 10; while (num > 0) { int digit = num % 10; if (digit > largest) { largest = digit; } num = num / 10; } return largest; }Show the solutionHide the solution
- Step 1: Combine the digit pattern with the maximum pattern.
- Step 2: Start
largestat a real digit, the last one (num % 10), so it's never an invented value. - Step 3: Each pass takes the last digit with
% 10, compares it withlargest, then drops it with/ 10. - Step 4: Trace 4829: the digits come out as 9, 2, 8, 4.
largeststarts at 9 and nothing beats it. - Step 5: Edge cases:
largestDigit(7)is 7 andlargestDigit(50)is 5. For 0, the loop never runs, and the method correctly returns0 % 10, which is 0.
Answer: The method above; it returns 9 for 4829, 7 for 7 and 5 for 50.
- Example 3
The average trap
What does this code print?
int sum = 0; int count = 0; for (int n = 1; n <= 10; n++) { if (n % 3 == 0) { sum += n; count++; } } double average = (double) sum / count; System.out.println(sum + " " + count + " " + average);Show the solutionHide the solution
- Step 1: The loop checks 1 through 10 and keeps the multiples of 3: 3, 6 and 9.
- Step 2:
sumis 18 andcountis 3. - Step 3:
(double) sum / countcastssumto 18.0 first, so the division is 18.0 / 3, which is 6.0. Without the cast,sum / countwould be theint6 and print as6.
Answer: It prints
18 3 6.0.
Common mistakes
- Starting a maximum at 0. If all values are negative, the answer is wrong. Start with a real value from the data.
- Dividing two
ints for an average and losing the decimal part. Cast one of them todoublefirst. - Returning from inside the loop too early, before every value has been checked.
- Writing
%when you meant/, or the other way around, when pulling out digits.
On the exam
- Since the 2025 course update, free-response Question 1 (Methods and Control Structures) is worth 7 points instead of 9: 4 for Part A and 3 for Part B. Part A usually needs one of these loop patterns. Name the pattern first, then write it.
- The exam is now digital, so you type your free-response answers in Bluebook instead of writing them by hand. Nothing runs your code for you, so trace it once with the example from the question before you move on.
Connected topics
Videos
Check yourself
4 questions on 2.9 Implementing Selection and Iteration Algorithms. Pick an answer to see if you got it, and why.
Consider the following method.public static int sumDigits(int n)
{
int sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}What value is returned by the call sumDigits(4096)?
Consider the following method.public static int reverse(int n)
{
int rev = 0;
while (n > 0)
{
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}What value is returned by the call reverse(1230)?
Consider the following code segment.int count = 0;
for (int k = 1; k < 20; k++)
{
if (k % 3 == 0 || k % 5 == 0)
{
count++;
}
}
System.out.println(count);What is printed as a result of executing the code segment?
Consider the following code segment.int count = 0;
for (int k = 1; k <= 30; k++)
{
if (k % 4 == 0 && k % 6 != 0)
{
count++;
}
}
System.out.println(count);What is printed as a result of executing the code segment?
0 of 4 answered