Skip Top Navigation Bar

Iterating over an Array an AP Computer Science A Topic

Iterating Over an Array

Using a For Loop

One way to iterate over the elements of an array is to use a for loop to iterate over the indices of the array. Since the indices of an array start at 0 and go to length - 1, we will set up our for loop to count from 0 to length - 1 .

int[] grades = {80, 70, 90, 95};
for (int index = 0; index < grades.length; index++) {
    IO.println(grades[index]);
}

Your Turn

Let's try it in the Java Playground.

Using an Enhanced For Loop to Iterate Over Values

An enhanced for loop can be used to iterate over all the values of the array instead of the indicies. Using the enhanced for loop means that the values are directly accessed without the need for square brackets.

NOTE: You can not modify the values of an array using an enhanced for loop. If you want to modify the values, use a regular for loop or while loop structure.

The structure of an enhanced for loop to iterate over an array is as follows:

<type of values> [] nameOfArray = {<list of values>};
for (<type of values> variable : nameOfArray) {
    //whatever you want to do with the elements
}

Your Turn

Let's try it in the Java Playground.

Resources