Selection and iteration 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, 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 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.
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 == 0tests whetherais evenly divisible byb; remember to guard against a divisor of 0.- Extract digits right to left with
n % 10for the last digit andn / 10(integer division) to drop it, looping whilen > 0. - Frequency counting follows one shape: start a counter at 0, loop, use an
ifto check your condition, and increment when true. - For min or max, initialize a tracker, then update 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
doubleto keep decimals. - Watch edge cases the exam loves: empty data, a count of 0, off-by-one loop bounds, and negative inputs in digit loops.
Core Algorithm Patterns
Checking Divisibility
The modulo operator % gives the remainder after division. 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 (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 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 idea is not limited to numbers. You can build up a String with concatenation 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 of each variable's value after every loop iteration. For digit extraction, 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, parameters, 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 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 < 10andi <= 10count different ranges, so pick the bound on purpose and trace a small case. - These patterns do not require arrays. Arrays are a Unit 4 extension; in this topic you apply the same logic to single values, digits, and ranges driven by loops.
Related AP Computer Science A Guides
Vocabulary
The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.Term | Definition |
|---|---|
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. |
Frequently Asked Questions
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.