The Stacks
UNIT 2: SELECTION AND ITERATION · TOPIC 2.9

2.9 Implementing Selection and Iteration Algorithms

The CED lists specific algorithms you should be able to write and recognize. These are the shapes FRQ 1 is built from.

What you need to know

  • Named algorithms the CED expects: compute a sum or average; count values meeting a condition; find the minimum or maximum; check whether a number is even/odd or divisible; compute the digits of an integer; determine whether a number is prime; find the frequency of a condition.
  • Sum/count pattern: initialize to 0 before the loop, update inside. Average = sum ÷ count, cast to double if needed.
  • Max/min pattern: initialize to the first value (or an extreme like Integer.MIN_VALUE), compare each value, replace if better.
  • Digit extraction: n % 10 is the last digit; n / 10 removes it. Loop while n > 0.
  • Divisibility: a % b == 0. Prime: loop from 2 to n−1 (or √n) checking for a divisor; if none, prime.
  • Early exit: a return inside the loop ends the method at the first match — used in "is there any…" checks.

Worked example

// sum of the digits of a positive int
public static int digitSum(int n)
{
    int sum = 0;
    while (n > 0)
    {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
// digitSum(4712): 2, then 1, then 7, then 4 → 14

// is n prime?
public static boolean isPrime(int n)
{
    if (n < 2) return false;
    for (int d = 2; d < n; d++)
    {
        if (n % d == 0) return false;
    }
    return true;
}
Exam tip: On FRQ 1, the rubric gives separate points for the loop, the condition, the update, and the return. Even if the logic isn't perfect, a correctly structured loop with the right variable initialized earns credit. Write the skeleton first, then fill in the condition.

Going deeper

The nuance, edge cases, and connections that turn a 3 into a 5.

  • The CED's named algorithms for this topic: compute a sum, average, minimum, or maximum of a set of numbers; count values with a property; determine even/odd or divisibility; process the digits of an integer; determine whether a number is prime; compute the frequency of a condition. FRQ 1 draws directly from these.
  • Accumulator initialization: sum starts at 0, product at 1, count at 0, max at the first value (or Integer.MIN_VALUE), min at the first value (or Integer.MAX_VALUE). Wrong initialization is the most common logic error the exam plants.
  • Average needs a double: (double) sum / count or sum / (double) count. Casting after dividing ((double) (sum / count)) is the trap — the truncation already happened.
  • Digit processing: while n > 0: last digit is n % 10; drop it with n /= 10. This processes digits right to left. Count digits, sum them, reverse the number, check for a digit — all this loop.
  • Prime check: n < 2 is not prime. For d from 2 to n − 1 (or to √n), if n % d == 0, not prime. If the loop completes, prime. Early return inside the loop is the clean way.
  • Divisibility: a % b == 0. Even: n % 2 == 0. Multiple of 5: n % 5 == 0.
  • FRQ 1 rubric shape: points for the loop header, the correct condition, the correct update/accumulation, and the return. Structure earns points even when a detail is off — so always write the full skeleton.

Mistakes that cost points

  • max = 0 for a list that could be all negative. Initialize to the first element.
  • Integer average. sum / count with two ints truncates. Cast one operand.
  • Prime loop that starts at 1. Every number is divisible by 1. Start at 2.
  • Processing digits with a for loop over a String. Works, but the CED's method is % and /. Know both.

Practice questions

Written in the style of the real exam. Try each one before revealing the answer.

Q1 What does the following method return when called with n = 3407?
public static int mystery(int n)
{
    int count = 0;
    while (n > 0)
    {
        if (n % 10 % 2 == 1)
        {
            count++;
        }
        n /= 10;
    }
    return count;
}
  1. A 2
  2. B 3
  3. C 4
  4. D 14
Show answer

Answer: A. It counts odd digits. Digits 7, 0, 4, 3: odd ones are 7 and 3 → 2.

Q2 The following code is intended to find the largest value among a, b, and c.
int max = 0;
if (a > max) max = a;
if (b > max) max = b;
if (c > max) max = c;
For which inputs does it give the wrong answer?
  1. A When all three are positive
  2. B When all three are negative
  3. C When two values are equal
  4. D It is always correct
Show answer

Answer: B. If all values are negative, none exceed 0, so max stays 0 — wrong. Initialize to a first value instead.

Key vocabulary

Accumulator
a variable that collects a running total or count across iterations
Digit extraction
using % 10 and / 10 to process an integer's digits