Skip to main content

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.

  1. Example 1

    Write a method: counting multiples

    Write a method countMultiples(int low, int high, int d) that returns how many integers from low to high, inclusive, are divisible by d. Assume d is 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 solution
    1. Step 1: This is the counting pattern: a counter that starts at 0, a loop over every value, and an if that adds 1 when the condition holds.
    2. Step 2: "Inclusive" means high must be checked too, so the condition is n <= high, not n < high.
    3. Step 3: The condition is divisibility: n % d == 0.
    4. Step 4: Return the count after the loop ends, not inside it.
    5. 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) returns 3.

  2. 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 solution
    1. Step 1: Combine the digit pattern with the maximum pattern.
    2. Step 2: Start largest at a real digit, the last one (num % 10), so it's never an invented value.
    3. Step 3: Each pass takes the last digit with % 10, compares it with largest, then drops it with / 10.
    4. Step 4: Trace 4829: the digits come out as 9, 2, 8, 4. largest starts at 9 and nothing beats it.
    5. Step 5: Edge cases: largestDigit(7) is 7 and largestDigit(50) is 5. For 0, the loop never runs, and the method correctly returns 0 % 10, which is 0.

    Answer: The method above; it returns 9 for 4829, 7 for 7 and 5 for 50.

  3. 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 solution
    1. Step 1: The loop checks 1 through 10 and keeps the multiples of 3: 3, 6 and 9.
    2. Step 2: sum is 18 and count is 3.
    3. Step 3: (double) sum / count casts sum to 18.0 first, so the division is 18.0 / 3, which is 6.0. Without the cast, sum / count would be the int 6 and print as 6.

    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 to double first.
  • 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

  • AP CSA Unit 2 Loops (2025)

    PickcodeWatch on YouTube (opens in a new tab)

  • 2026 AP Computer Science A Exam Review - Exploring FRQ 1: Methods and Control Structures (Revised)

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • Java Program #12 - Reverse a Number in Java

    Programming For BeginnersWatch on YouTube (opens in a new tab)

  • Find Sum of Digits of a Number - Java Code

    Programming TutorialsWatch on YouTube (opens in a new tab)

Check yourself

4 questions on 2.9 Implementing Selection and Iteration Algorithms. Pick an answer to see if you got it, and why.

Question 1 of 4

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)?

Question 2 of 4

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)?

Question 3 of 4

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?

Question 4 of 4

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