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.
- Predict the output.
- Run the code to determine if your prediction is correct.
- Modify the code so that each value in
grades is added to total.
- Predict the output and run your code to determine if it is correct.
- Modify the code so to compute the average of the values in
grades.
- Predict the output and run your code. The average should be
81.
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.
- Predict the output.
- Run the code to determine if your prediction is correct.
- Modify the code so that each value in
grades is added to total.
- Predict the output and run your code to determine if it is correct.
- Modify the code so to compute the average of the values in
grades.
- Predict the output and run your code. The average should be
81.
Resources