Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

3.4: Accumulators and Counters

A counter records how many items satisfy a condition; an accumulator combines their values. Initialize both outside the traversal.

College Board Unit 2

How it works

An accumulator builds a running total across a loop, while a counter tracks how many times a condition was met. Both share the same structure: declare and initialize before the loop, update conditionally inside it, and read the result after the loop ends. Sum accumulators start at 0, product accumulators start at 1, and counters start at 0.

Write in words what the accumulator holds after processing index i, then check the initialization satisfies that for the empty case.

Common error

Initializing a running maximum to zero, which fails whenever all values are negative.

Worked example

Java

int count = 0;
int sum = 0;
for (int n = 1; n <= 6; n++) {
    if (n % 2 == 0) { count++; sum += n; }
}
System.out.println(count + ":" + sum);

Output

3:12

Three even values qualify, and their values sum to 12.

Exercises

3.4.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

int product = 1;
for (int n = 2; n <= 4; n++) product *= n;
System.out.println(product);
Show solution

Output

24

A product accumulator starts at the multiplicative identity 1, not 0.

3.4.2 · Write code

Given {3, -2, 0, 7, -1}, count and sum the positive values. Print the count followed by a colon and the sum.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

int[] values = {3, -2, 0, 7, -1};
int count = 0;
int sum = 0;
for (int value : values) {
    if (value > 0) { count++; sum += value; }
}
System.out.println(count + ":" + sum);
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic