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:12Three 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
24A 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);