The Accumulator Pattern

The accumulator pattern is a simple loop-based algorithm that combines many values into one result. You create a variable (the accumulator), start it at a safe initial value, and update it as you traverse an array or list.

This pattern powers common tasks on the AP CSA exam: sum, average, minimum, maximum, and counting items that match a condition.


When To Use It

Use an accumulator any time you need one number after scanning a collection:

  • Total points or sales across days
  • Average quiz score
  • Smallest or largest value seen so far
  • How many values meet a rule (for example, at least 80)

It works with arrays, ArrayList, and Strings (counting characters, vowels, etc.).


Worked Example

Suppose you have quiz scores:

scores = [7, 9, 5, 10, 8, 6]

Goal 1: average score
Goal 2: count how many scores are at least 8
Goal 3: smallest score

Step by step for the count (scores ≥ 8):

  1. Start count at 0
  2. See 7 → rule fails → count stays 0
  3. See 9 → rule passes → count becomes 1
  4. See 5 → rule fails → count stays 1
  5. See 10 → rule passes → count becomes 2
  6. See 8 → rule passes → count becomes 3
  7. See 6 → rule fails → count stays 3

Final count is 3.

For the minimum:

  1. Start min at the first element, 7
  2. Compare 9 → min stays 7
  3. Compare 5 → new min is 5
  4. Compare 10 → min stays 5
  5. Compare 8 → min stays 5
  6. Compare 6 → min stays 5

Final min is 5.

The average is sum / length. Sum is 7 + 9 + 5 + 10 + 8 + 6 = 45.
Average = 45 / 6 = 7.5.


Annotated Java (AP CSA subset)

public class Accumulators {

    // Returns the average of all elements in a (assumes a.length > 0)
    public static double average(int[] a) {
        int sum = 0; // accumulator starts at 0
        for (int value : a) { // enhanced for: traverses all elements
            sum += value; // update accumulator
        }
        // cast to double so we do real division, not integer division
        return (double) sum / a.length;
    }

    // Returns the smallest element in a (assumes a.length > 0)
    public static int min(int[] a) {
        int currentMin = a[0]; // safe start: first element
        for (int i = 1; i < a.length; i++) {
            // update when we see a smaller value
            if (a[i] < currentMin) { 
                currentMin = a[i];
            }
        }
        return currentMin;
    }

    // Counts how many elements are at least the threshold
    public static int countAtLeast(int[] a, int threshold) {
        int count = 0;                    // accumulator for the count
        for (int x : a) {
            if (x >= threshold) {
                count++;                  // increase when rule passes
            }
        }
        return count;
    }

    // Small demo you can run locally
    public static void main(String[] args) {
        int[] scores = {7, 9, 5, 10, 8, 6};
        System.out.println(average(scores));              // 7.5
        System.out.println(min(scores));                  // 5
        System.out.println(countAtLeast(scores, 8));      // 3
    }
}

Notes:

  • The AP CSA subset allows arrays, loops, if statements, and the enhanced for loop.
  • These methods assume the array is nonempty, which is standard on the exam unless stated otherwise.

Time and Space Complexity

Each method visits every element exactly once.
Time: O(n), where n is the array length.
Space: O(1), because only a few variables are used regardless of n.


Common Pitfalls

  • Integer division in averages. If both sum and length are int, sum / length truncates. Cast first: (double) sum / a.length.
  • Unsafe min/max initialization. Starting min at 0 fails for all-negative arrays. Start with the first element (a[0]) and loop from index 1.
  • Off-by-one errors. The standard index loop is for (int i = 0; i < a.length; i++). Do not use <=.
  • Resetting the accumulator inside the loop. The accumulator should be initialized once before the loop, then updated inside.
  • Using =+ instead of +=. sum =+ value sets sum to positive value; sum += value adds to sum.

Why This Matters On The Exam

Many free-response parts boil down to traverse and accumulate. If you can write these patterns quickly and safely, you save time and avoid bugs. The same structure extends to ArrayList and to traversing 2D arrays (with a nested loop).


Practice

  1. What does the following method return on the array {4, 12, 9, 12, 5}?

countAtLeast(a, 10)

  1. Consider this code to compute an average:

int sum = 0;
for (int x : a) { sum += x; }
double avg = sum / a.length;

Explain the bug and fix it in one line.


Answer Key

  1. The values at least 10 are 12 and 12. The method returns 2.
  2. sum / a.length uses integer division because both are int, so decimals are lost. Fix:

double avg = (double) sum / a.length;

This forces real division and keeps the fractional part.

Leave a comment