π6.2: Arrays & For Loops
Table of Contents
π This page is a condensed version of CSAwesome Topic 6.2
Traversing Arrays with For Loops
Index Variables
In the last lesson, we mentioned that you can use a variable for the index of an array. You can even do math with that index and have an arithmetic expression inside the [], like below.
// highScores array declaration
int[] highScores = { 10, 9, 8, 8};
// use a variable for the index
int index = 3;
// modify array value at index
highScores[index] = 11;
// print array value at index
System.out.println( highScores[index] );
System.out.println( highScores[index - 1] );
π¬ DISCUSS: What does the code above print out? You can follow the code in this Java Visualizer and look at the image depicting the array below.
What do you think the following code will print out? First trace through it on paper keeping track of the array and the index variable. Then, run it to see if you were right. You can also follow it in the Java Visualizer.
String[] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"};
int index = 1;
System.out.println(names[index - 1]);
index++;
System.out.println(names[index]);
System.out.println(names[index / 2]);
names[index] = "Rafi";
index--;
System.out.println(names[index + 1]);
For Loop to Traverse Arrays
We can use iteration with a standard for loop to βvisitβ each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.
Note that the variable i (short for index) is often used in loops as the loop counter variable and is used here to access each element of an array with its index (position).
For example, here is a loop traversing the highScores
array to print every score. Follow the code below in the Java Visualizer.
int[] highScores = { 10, 9, 8, 11};
for (int i = 0; i < highScores.length; i++) {
System.out.println( highScores[i] );
}
Using a variable as the index is a powerful data abstraction feature because it allows us to use loops with arrays where the loop counter variable is the index of the array! This allows our code to generalize to work for the whole array.
What do you think the following code will print out? First trace through it on paper keeping track of the array and the index variable. Then, run it to see if you were right.
String[] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"};
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
Try adding your name and a friendβs name to the array names and run the code again. Did the code work without changing the loop?
Modifying Values in an Array
The following code demonstrates a loop that changes the values in an array. In this code, the array is passed as an argument to the static methods in the class. You can try the code in the Java Visualizer.
public static void multAll(int[] values, int amt) {
for (int i = 0; i < values.length; i++) {
values[i] = values[i] * amt;
}
}
public static void printValues(int[] values) {
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
public static void main(String[] args) {
int[] numArray = {2, 6, 7, 12, 5};
multAll(numArray, 2);
printValues(numArray);
}
π¬ DISCUSS: What do these methods do? Trace through it, keeping track of the array values and the output.
Arrays in Java are objects, so the array variables are references to an address in memory. When an array is passed as an argument to a method, the name of the array refers to its address in memory. Therefore, any changes to the array in the method will affect the original array.
Since arrays can be very large, we do not want to copy them entirely when we pass them into methods.
Looping Backwards
β¬ οΈ You donβt have to loop through an array from the front to the back, you can loop by starting at the final index of the array and move toward the front during each time through the loop.
In the example below, the method getIndexOfLastSmallerItem
returns the index of the last element in the array that is smaller than the given argument (the βtargetβ).
public static int getIndexOfLastSmallerItem(int[] values, int target) {
for (int index = values.length - 1; index >= 0; index--) {
if (values[index] < target) {
return index;
}
}
return -1;
}
The return statement inside the loop stops the execution of the loop and the method and returns the index that is found immediately back to the main method. It returns
-1
if there is no number in the array that is smaller than the given number.
Can you add another method that finds the index of the last element greater than the target, instead of smaller, and have your main
method print out a test of it?
Call this method getIndexOfLastGreaterItem
and give it 2 arguments and a return value like the method above.
Common Errors When Looping Through an Array
Off by one errors, where you go off the array by 1 element, are easy to make when traversing an array which result in an ArrayIndexOutOfBoundsException
being thrown.
When attempting to process (βvisitβ) all array elements, be careful to start at the first index which is 0
and end at the last index.
- Usually loops are written so that the index starts at 0, and continues while the index is less than
arrayName.length
since (arrayName.length - 1
) is the index for the last element in the array.- Make sure you do not use
<=
instead of<
! If the index is less than 0 or greater than (arrayName.length - 1
), anArrayIndexOutOfBoundsException
will be thrown.
- Make sure you do not use
π» In-Class Activity: SpellChecker
π² Practice Game: Loops with Arrays
Try the game below to practice! Click on Arrays and click on the element of the *
array that would be printed out by the given code. If youβre stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get.
βοΈ Summary
-
Iteration (loops) can be used to access all the elements in an array, traversing the array.
-
Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
-
Since the index for an array starts at 0 and end at the number of elements β 1, βoff by oneβ errors are easy to make when traversing an array, resulting in an ArrayIndexOutOfBoundsException being thrown.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.