01 / 20

Array Iteration
& Aggregates

Learn to traverse arrays with loops and compute aggregates like sum, average, min, and max in Java.

AP Computer Science Java

What Is an Array?

An array is a fixed-size, ordered collection of elements that share the same type. Each element lives at a numbered position called an index, starting at \( 0 \).

3
7
1
9
4
6
0
1
2
3
4
5

Why Iterate Through Arrays?

Arrays often hold data that we need to process element-by-element: computing totals, searching for values, or transforming entries. A loop lets us visit every element systematically.

Sum / Average
Add all values, then divide by length to find the mean.
Min / Max
Track the smallest or largest value seen so far as you scan.
Search / Count
Check each element against a condition and tally matches.

What Is an Aggregate?

An aggregate is a single value computed from an entire collection. In Java, we build aggregates by iterating through an array and updating an accumulator variable on each step.

3 7 1 9 4 24 iterate & accumulate
\( \text{sum} = 3+7+1+9+4 \)

The for Loop Pattern

The standard indexed for loop is the most common way to traverse an array in Java. It gives you full control over the index variable i.

for (int i = 0; i < arr.length; i++) {
    // process arr[i]
}

The for-each Loop

Java's enhanced for loop (for-each) simplifies iteration when you don't need the index. It reads each element directly into a variable.

for (int val : arr) {
    // process val
}

for vs for-each

Standard for Enhanced for-each
Access to index Yes No
Can modify elements Yes No
Readability More verbose Cleaner
Best for aggregates When index matters Simple sum/min/max
Traverse backwards Yes No

How to Compute an Aggregate

1
Initialize an accumulator before the loop (e.g., sum = 0 or max = arr[0]).
2
Loop through every element using a for or for-each loop.
3
Update the accumulator inside the loop body (add to sum, compare for min/max, etc.).
4
Use the result after the loop ends. For average, divide sum by arr.length.

Example: Computing the Sum

int[] scores = {85, 92, 78, 95, 88};
int sum = 0;

for (int s : scores) {
    sum += s;
}

System.out.println(sum); // 438

Example: Computing the Average

int[] scores = {85, 92, 78, 95, 88};
int sum = 0;

for (int s : scores) {
    sum += s;
}

double avg = (double) sum / scores.length;
System.out.println(avg); // 87.6

Example: Finding Min and Max

int[] vals = {14, 3, 27, 8, 19};
int min = vals[0];
int max = vals[0];

for (int v : vals) {
    if (v < min) min = v;
    if (v > max) max = v;
}

System.out.println("Min: " + min); // Min: 3
System.out.println("Max: " + max); // Max: 27

Example: Counting Matches

int[] temps = {72, 68, 81, 75, 90, 65, 88};
int count = 0;

for (int t : temps) {
    if (t >= 80) {
        count++;
    }
}

System.out.println(count); // 3
72
68
81
75
90
65
88
0
1
2
3
4
5
6

When the Index Matters

Sometimes you need the position of an element, not just its value: finding where the max occurs, or comparing adjacent pairs.

int[] arr = {5, 12, 8, 20, 3};
int maxIdx = 0;

for (int i = 1; i < arr.length; i++) {
    if (arr[i] > arr[maxIdx]) {
        maxIdx = i;
    }
}

System.out.println("Max at index: " + maxIdx); // 3

Common Mistakes

✕ Off-by-One Error
Using i <= arr.length causes an ArrayIndexOutOfBoundsException. The last valid index is arr.length - 1.
✕ Init Min/Max to 0
If all elements are negative, max = 0 stays 0 and never updates. Initialize to arr[0] instead.
✕ Integer Division
Writing sum / arr.length when both are int truncates the decimal. Cast one operand to double.

Aggregate Cheat Sheet

Aggregate Init Value Loop Body After Loop
Sum sum = 0 sum += v Use sum
Average sum = 0 sum += v (double)sum/n
Min min = arr[0] if(v<min) min=v Use min
Max max = arr[0] if(v>max) max=v Use max
Count count = 0 if(cond) count++ Use count

Question 1 of 5

What is printed by this code?

int[] a = {4, 1, 7, 2};
int sum = 0;
for (int x : a) {
    sum += x;
}
System.out.println(sum);

Question 2 of 5

Which loop should you use if you need to replace each element with its double?

Question 3 of 5

What value does min hold after this code runs?

int[] data = {-3, -7, -1, -5};
int min = 0;
for (int d : data) {
    if (d < min) min = d;
}

Question 4 of 5

What is the output of this code?

int[] nums = {10, 20, 30};
int result = 0;
for (int i = 0; i <= nums.length; i++) {
    result += nums[i];
}
System.out.println(result);

Question 5 of 5

Given int[] arr = {5, 10, 15};, what does (double) sum / arr.length evaluate to when sum = 30?