---
title: "Selection and Iteration Algorithms | AP CSA 2.9"
description: "Review AP CSA selection and iteration algorithms, including divisibility, digit extraction, frequency counting, min/max tracking, sums, and averages."
canonical: "https://fiveable.me/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU"
type: "study-guide"
subject: "AP Computer Science A"
unit: "Unit 2 – Selection and Iteration"
lastUpdated: "2026-06-09"
---

# Selection and Iteration Algorithms | AP CSA 2.9

## Summary

Review AP CSA selection and iteration algorithms, including divisibility, digit extraction, frequency counting, min/max tracking, sums, and averages.

## Guide

[Selection and iteration](/ap-comp-sci-a/unit-2 "fv-autolink") algorithms combine `if` statements with loops to solve standard problems before arrays enter the course. Core patterns include checking divisibility with `%`, extracting digits with `%` and `/`, counting matches, tracking a running min or max, and building a sum or average. For [AP Computer Science A](/ap-comp-sci-a "fv-autolink"), identify the pattern first, then trace the loop and condition together.

## What Are Selection and Iteration Algorithms in AP CSA?

Selection and iteration algorithms are code patterns that combine `if` statements with loops to solve common problems. In AP CSA Topic 2.9, the standard patterns include checking divisibility, extracting digits, counting matches, finding a minimum or maximum, and computing a sum or average.

## Why This Matters for the AP Computer Science A Exam

These algorithms are some of the most reusable patterns in the whole course. On the multiple-choice section, you will trace code that processes digits, counts matches, or accumulates a total and predict the exact output. On the free-response code-writing questions, you often need to write [methods](/ap-comp-sci-a/unit-3/abstraction-and-program-design/study-guide/o9VgVeIpKRYZ7N7rXfUz "fv-autolink") that use iterative and conditional statements together, which is exactly what these algorithms do. Building fluency here also sets you up for later units, where the same min, max, count, and sum ideas reappear with arrays, ArrayLists, and [2D arrays](/ap-comp-sci-a/unit-4/2d-arrays/study-guide/5WDx6ZFeWhx2aVuiZI6R "fv-autolink").

The key skills this topic supports are writing code to implement an algorithm, determining output based on execution order, and describing what a code segment does. All three show up directly on the exam.

## Key Takeaways

- `a % b == 0` tests whether `a` is evenly divisible by `b`; remember to guard against a divisor of 0.
- Extract digits right to left with `n % 10` for the last digit and `n / 10` ([integer division](/ap-comp-sci-a/key-terms/integer-division "fv-autolink")) to drop it, [looping](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe "fv-autolink") while `n > 0`.
- Frequency counting follows one shape: start a counter at 0, loop, use an `if` to check your condition, and increment when true.
- For min or max, initialize a tracker, then [update](/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt "fv-autolink") it whenever you find a value that beats the current one.
- Sums start at 0 and add each value; to get an average, divide by the count and cast to `double` to keep decimals.
- Watch edge cases the exam loves: empty data, a count of 0, off-by-one loop [bounds](/ap-comp-sci-a/key-terms/bounds "fv-autolink"), and negative inputs in digit loops.

## Core Algorithm Patterns

### Checking Divisibility

The [modulo operator](/ap-comp-sci-a/key-terms/modulo-operator "fv-autolink") `%` gives the remainder after [division](/ap-comp-sci-a/unit-1/expressions-and-assignment-statements/study-guide/01dr6uUPDAn3SjtK2Psr "fv-autolink"). When `a % b` equals 0, `a` is evenly divisible by `b`. That single check powers a lot of logic: a number is even when `n % 2 == 0`, and it ends in 0 when `n % 10 == 0`.

Because modulo returns a remainder, `17 % 5` is 2 (17 is 5 times 3 with 2 left over). If `b` could be 0, check for that first, since dividing or taking the remainder by 0 causes an error.

```java
// Check if a is divisible by b
public static boolean isDivisible(int a, int b) {
    if (b == 0) return false;  // Avoid division by zero
    return a % b == 0;
}

// Count how many numbers in a range are divisible by factor
public static int countDivisible(int start, int end, int factor) {
    int count = 0;
    for (int i = start; i <= end; i++) {
        if (i % factor == 0) {
            count++;
        }
    }
    return count;
}
```

### Extracting Individual Digits

To work with individual digits, combine `%` and integer division. The last digit of any number is `n % 10`. Dividing by 10 with integer division shifts the remaining digits right. Repeat until the number reaches 0, and you process digits from right to left.

For 1234: `1234 % 10` is 4, then `1234 / 10` is 123, then `123 % 10` is 3, and so on. This is the base of digit sums, digit counts, and reversing numbers. The pattern works because our number system is base 10.

```java
// Sum all digits in a number
public static int sumDigits(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;  // Add last digit
        n /= 10;        // Remove last digit
    }
    return sum;
}

// Count how many times a digit appears
public static int countDigit(int number, int target) {
    int count = 0;
    while (number > 0) {
        if (number % 10 == target) {
            count++;
        }
        number /= 10;
    }
    return count;
}
```

One thing to watch: a `while (n > 0)` loop never runs for a negative number. If a problem allows negatives, handle the sign first (for example, flip it with `n = -n`).

### Counting Frequencies

Frequency counting uses a counter that increases each time a condition is true. The shape is always the same: start `count` at 0, loop through your values, check a condition with an `if`, and add 1 when it holds. After the loop, the counter holds the total. This is [iteration](/ap-comp-sci-a/unit-2/while-loops/study-guide/7qGsGOh1UKALAWpJhZOi "fv-autolink") (the loop) plus selection (the `if`) working together.

```java
// Count values that pass a threshold while reading numbers
public static int countAboveThreshold(int low, int high, int threshold) {
    int count = 0;
    for (int value = low; value <= high; value++) {
        if (value > threshold) {
            count++;
        }
    }
    return count;
}
```

### Finding Minimum and Maximum

To find an extreme value, keep a variable that tracks the current min or max and update it as you go. For a maximum, replace the tracker whenever a value is larger; for a minimum, replace it whenever a value is smaller. The comparison is the only thing that changes between the two.

[Initialization](/ap-comp-sci-a/key-terms/initialization "fv-autolink") matters. You can start the tracker with the first value you see, or start a max search at `Integer.MIN_VALUE` and a min search at `Integer.MAX_VALUE` so the first real value always updates it.

```java
// Track the largest digit in a number
public static int largestDigit(int n) {
    if (n < 0) n = -n;
    if (n == 0) return 0;

    int max = 0;  // digits are 0-9, so 0 is a safe starting point
    while (n > 0) {
        int digit = n % 10;
        if (digit > max) {
            max = digit;
        }
        n /= 10;
    }
    return max;
}
```

### Computing Sums and Averages

Accumulation builds a result across loop iterations. For a sum, start at 0 and add each value. To get an average, divide the sum by the count. Be careful with integer division: if both the sum and the count are `int`, the result is truncated. Cast to `double` when you need decimals, and check for a count of 0 before dividing to avoid a division-by-zero error.

```java
// Average of the integers from low to high (inclusive)
public static double averageInRange(int low, int high) {
    int count = high - low + 1;
    if (count <= 0) return 0.0;  // guard against an empty range

    int sum = 0;
    for (int value = low; value <= high; value++) {
        sum += value;
    }
    return (double) sum / count;  // cast keeps the decimals
}
```

The [accumulator](/ap-comp-sci-a/key-terms/accumulator "fv-autolink") idea is not limited to numbers. You can build up a `String` with [concatenation](/ap-comp-sci-a/unit-1/string-methods/study-guide/SltCtk8JxBIgHcMfG6G4 "fv-autolink") or track a running statistic. The point is keeping state across iterations.

> Later in Unit 4, these same min, max, count, sum, and average patterns reappear when you loop over arrays and ArrayLists. The logic is identical; only the way you read each value changes. For now, focus on scalars, loops, and conditionals.

## How to Use This on the AP Computer Science A Exam

### Code Tracing

When you trace digit or accumulation code, keep a small [table](/ap-comp-sci-a/unit-4/introduction-to-using-data-sets/study-guide/fq4I4p0XINBBV56xQfTx "fv-autolink") of each variable's value after every loop iteration. For [digit extraction](/ap-comp-sci-a/key-terms/digit-extraction "fv-autolink"), write down `n`, `n % 10`, and the new `n / 10` each pass. This catches the most common errors instantly.

```java
// Trace sumDigits(1234)
// n=1234 -> sum += 4 -> sum=4,  n=123
// n=123  -> sum += 3 -> sum=7,  n=12
// n=12   -> sum += 2 -> sum=9,  n=1
// n=1    -> sum += 1 -> sum=10, n=0  (loop stops)
// returns 10
```

### Free Response

Free-response code-writing prompts frequently ask for methods that combine loops and conditionals, sometimes alongside `String` methods. When the task is "find the maximum," "count how many," or "compute the average," reach for the exact standard pattern. Read the prompt closely and underline the [return type](/ap-comp-sci-a/key-terms/return-type "fv-autolink"), [parameters](/ap-comp-sci-a/unit-4/recursion/study-guide/p4D3YegZCLwQ3KJVvsd4 "fv-autolink"), and the condition you are counting or comparing against, so you do not miss a detail.

### Common Trap

Integer division silently truncates. If a method should return a decimal average, cast to `double` before dividing. Also confirm your loop bounds: decide whether the endpoint should be included (`<=`) or excluded (`<`) before you write the loop, then trace one small case to confirm.

```java
// WRONG: integer division loses the decimal
int sum = 255;
int count = 3;
double average = sum / count;       // 85.0, but truncation already happened

// CORRECT: cast first so the division keeps decimals
double averageFixed = (double) sum / count;  // 85.0 with no lost precision
```

## Common Misconceptions

- `%` does not tell you "how many times b goes into a." It gives the remainder. The quotient comes from integer division `/`.
- A `while (n > 0)` digit loop skips negative numbers entirely because the condition is false from the start. Handle the sign first if negatives are allowed.
- [Casting](/ap-comp-sci-a/unit-1/casting-and-ranges-of-variables/study-guide/kW3XXEIwJwVRXFx3ntdC "fv-autolink") after dividing two ints is too late. `(double)(sum / count)` still truncates first. Cast one operand before the division: `(double) sum / count`.
- Initializing a max search to 0 is only safe when every value is at least 0. For data that can be negative, start from the first value or `Integer.MIN_VALUE`.
- Off-by-one bounds change your answer. `i < 10` and `i <= 10` count different ranges, so pick the bound on purpose and trace a small case.
- These patterns do not require arrays. Arrays are a [Unit 4](/ap-comp-sci-a/unit-4 "fv-autolink") extension; in this topic you apply the same logic to single values, digits, and ranges driven by loops.

## Related AP Computer Science A Guides

- [2.1 Algorithms with Selection and Repetition](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe)
- [2.7 While Loops](/ap-comp-sci-a/unit-2/while-loops/study-guide/7qGsGOh1UKALAWpJhZOi)
- [2.6 Equivalent Boolean Expressions](/ap-comp-sci-a/unit-2/equivalent-boolean-expressions/study-guide/aMDnyFuOcAXnZigLW1vL)
- [2.11 Nested Iteration](/ap-comp-sci-a/unit-2/nested-iteration/study-guide/Buapg1KURHNbw6yRY8EZ)
- [2.12 Informal Code Analysis](/ap-comp-sci-a/unit-2/informal-code-analysis/study-guide/CR84MbOE4FDDoSVokDVZ)
- [2.8 For Loops](/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt)

## Vocabulary

- **algorithm**: A step-by-step procedure or set of rules designed to solve a problem or accomplish a task.
- **average**: The mean value calculated by dividing the sum of all values by the number of values.
- **evenly divisible**: A property of an integer that can be divided by another integer with no remainder.
- **frequency**: The number of times a specific criterion or condition is met within a dataset or sequence.
- **maximum value**: The largest value in a set of data or collection of numbers.
- **minimum value**: The smallest value in a set of data or collection of numbers.
- **standard algorithm**: A widely recognized, established procedure for solving a common computational problem.
- **sum**: The result of adding multiple values together.

## FAQs

### What are selection and iteration algorithms in AP CSA?

Selection and iteration algorithms combine conditionals with loops to solve common problems. AP CSA Topic 2.9 focuses on patterns like divisibility checks, digit extraction, frequency counting, min/max tracking, and sums or averages.

### How do you check divisibility in Java?

Use the modulo operator. If a % b equals 0, then a is evenly divisible by b. Make sure the divisor is not 0 before using % or /.

### How do you extract digits from an integer in Java?

Use n % 10 to get the last digit and integer division n / 10 to remove the last digit. Repeating that process in a loop lets you process digits from right to left.

### What is frequency counting in AP CSA?

Frequency counting means starting a counter at 0, looping through values, checking a condition with an if statement, and incrementing the counter each time the condition is true.

### How do min and max algorithms work?

A min or max algorithm keeps a tracker variable and updates it whenever a new value is smaller or larger than the current tracker. Good initialization matters, especially when values can be negative.

### What is the common average mistake in Java?

The common mistake is dividing two int values before casting, which truncates the decimal. Cast one operand to double before dividing, and avoid dividing by a count of 0.

## Structured Data

```json
{"@context":"https://schema.org","@type":"FAQPage","inLanguage":"en","mainEntity":[{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU#what-are-selection-and-iteration-algorithms-in-ap-csa","name":"What are selection and iteration algorithms in AP CSA?","acceptedAnswer":{"@type":"Answer","text":"Selection and iteration algorithms combine conditionals with loops to solve common problems. AP CSA Topic 2.9 focuses on patterns like divisibility checks, digit extraction, frequency counting, min/max tracking, and sums or averages."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU#how-do-you-check-divisibility-in-java","name":"How do you check divisibility in Java?","acceptedAnswer":{"@type":"Answer","text":"Use the modulo operator. If a % b equals 0, then a is evenly divisible by b. Make sure the divisor is not 0 before using % or /."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU#how-do-you-extract-digits-from-an-integer-in-java","name":"How do you extract digits from an integer in Java?","acceptedAnswer":{"@type":"Answer","text":"Use n % 10 to get the last digit and integer division n / 10 to remove the last digit. Repeating that process in a loop lets you process digits from right to left."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU#what-is-frequency-counting-in-ap-csa","name":"What is frequency counting in AP CSA?","acceptedAnswer":{"@type":"Answer","text":"Frequency counting means starting a counter at 0, looping through values, checking a condition with an if statement, and incrementing the counter each time the condition is true."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU#how-do-min-and-max-algorithms-work","name":"How do min and max algorithms work?","acceptedAnswer":{"@type":"Answer","text":"A min or max algorithm keeps a tracker variable and updates it whenever a new value is smaller or larger than the current tracker. Good initialization matters, especially when values can be negative."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU#what-is-the-common-average-mistake-in-java","name":"What is the common average mistake in Java?","acceptedAnswer":{"@type":"Answer","text":"The common mistake is dividing two int values before casting, which truncates the decimal. Cast one operand to double before dividing, and avoid dividing by a count of 0."}}]}
```
