AP® Computer Science Principles · Big Idea 3 · Topic 3.10
Standard List Algorithms: Sum, Average, Max, and Count
Standard list algorithms solve common tasks by walking through a list once, updating a running variable at each step. Sum, average, max, and count all follow this same one-pass pattern.
Each of these algorithms uses an accumulator: a variable that starts with some initial value and updates as the loop visits each element. For sum, you start a running total at 0 and add each element to it as you go. For count, you start at 0 and add 1 each time you see a qualifying element. For average, you do a sum pass, then divide by the count once the loop ends. None of these need to look back at earlier elements or make a second trip through the list, because the running variable already carries everything the algorithm needs to know so far.
Finding the maximum works the same way but compares instead of adds. You start a running maximum equal to the first element, then at each later element you ask: is this bigger than what I'm holding? If yes, replace the running maximum with it. If no, keep going. This is why one pass is enough: once you've compared every element against the current best, nothing is left that could beat it. Looking twice would just repeat comparisons already settled.
These algorithms matter because they're the building blocks for nearly every list-processing procedure in this unit. Once you can track a running value through a loop, you can adapt the same shape to find a minimum, search for a target, or filter elements that meet a condition. The idea of carrying state across iterations, rather than restarting work each time, is the core skill that connects loops to the more complex procedures that follow.
Key terms
- Accumulator
- A variable that collects a running result, such as a total or count, across loop iterations.
- Running maximum
- A variable holding the largest value seen so far as a loop moves through a list.
- One-pass algorithm
- An algorithm that visits each list element exactly once and still produces a correct result.
- Count
- The number of elements in a list, or the number meeting some condition, tracked with an accumulator.
Watch it explained
- How it worksHow does a running maximum update itself as the loop meets each new element?
- Worked exampleTrace finding the maximum of the list 7, 2, 11, 4, 11, 9 with a running maximum.
- Worked exampleFind the average of the list 4, 8, 15, 16, 23, 42 by summing and then dividing.
- Going furtherWhat changes about a maximum algorithm when the list handed to it is empty?
Check yourself
End of topic.