Topic 2.9 — Implementing Selection and Iteration Algorithms
Goal: combine if statements and loops to implement common algorithms like
counting, accumulating, finding extremes, and checking conditions.
The big idea
Real programs rarely use just one if or just one loop.
In AP CSA, you’ll often implement algorithms by combining:
selection (decisions) + iteration (repetition).
Think in patterns: count, sum, find best, stop when done.
Most common “algorithm patterns”
- Accumulate: build a total (sum/product)
- Count: how many items match a condition
- Find extreme: max/min
- Search: find whether a value exists
- Validate: keep asking until input is valid
Pattern 1: Accumulation (sum)
Add values over time using a loop.
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
// sum = 15
Pattern 2: Counting with a condition
Use an if inside a loop.
int countEven = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
countEven++;
}
}
// countEven = 5
Pattern 3: Find the maximum
Track the “best so far” while scanning values.
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
Pattern 4: Find if something exists
Search until found (often with a boolean flag).
boolean found = false;
int i = 0;
while (i < nums.length && !found) {
if (nums[i] == target) {
found = true;
}
i++;
}
Common mistakes
- Forgetting to update loop variables (infinite loop).
- Not initializing “best so far” correctly (max/min bugs).
- Off-by-one errors in loop bounds.
- Putting the update inside the if by accident.
// Bug: i only increments sometimes → may loop forever
while (i < n) {
if (condition) {
i++;
}
}
How to build these on the exam
- Decide what you’re tracking: sum? count? max? found?
- Initialize it correctly.
- Loop through the data (or repeat until done).
- Use
ifinside the loop to update when a condition matches. - Double-check bounds and updates.
Quick self-check
- What variable do you use for a “counting” algorithm?
- Why does max usually start as the first value, not 0?
- What two pieces prevent an infinite loop?
- Where does the
ifusually go when counting matches? - What’s the difference between “find max” and “search for target”?