6.2. Traversing Arrays with For Loops

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;
System.out.println(  highScores[index] );
System.out.println(  highScores[index - 1] );

coding exercise Coding Exercise

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.

Using variables 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!

We can use iteration (usually a for loop) to loop through all the elements 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.

int[] highScores = { 10, 9, 8, 8};
for (int i = 0; i < highScores.length; i++)
{
    System.out.println(  highScores[i] );
}

coding exercise Coding Exercise

What does the following code print out? Trace through it keeping track of the array values and the output. Then run it to see if you’re right. Notice that in this code, the array is a private instance variable of the class ArrayWorker. It is created in the constructor and changed or accessed by the methods. You can also try the code in the Java visualizer to see it running step by step as you hit Forward.

exercise Check Your Understanding

        6-2-1: The following method has the correct code to subtract amt from all the values in the array values (a field of the current object), but the code is mixed up.  Drag the blocks from the left into the correct order on the right and indent them correctly. You will be told if any of the blocks are in the wrong order or not indented correctly.public void subAll(int amt)
{
---
   for (int i = 0;
        i < values.length;
        i++)
   {
---
      values[i] = values[i] - amt;
---
   } // end for loop
---
} // end method
        

6.2.1. Looping From Back to Front

You don’t have to loop through an array from the front to the back. You can loop by starting at the back of the array and move toward the front during each time through the loop. This can be handy when you are looping through a sorted array and want to find the index of the last number that is less than some given number as shown in the method getIndexLastSmaller below. Notice that the method returns -1 if there is no number in the array that is smaller than the given number. Why does this work?

coding exercise Coding Exercise

What does the following code print out? Trace through it keeping track of the array values and the output. Then run it to see if you’re right. Notice that in this code, the array is a private instance variable of the class ArrayWorker. It is created in the constructor and changed or accessed by the methods. You can also try the code in the Java visualizer.

exercise Check Your Understanding

    6-2-2: Given the following code segment what will be returned when you execute: getIndexLastSmaller(-13);

    private int[ ] values = {-20, -15, 2, 8, 16, 33};
    
    public int getIndexLastSmaller(int compare)
    {
       for (int i = values.length - 1; i >=0; i--)
       {
          if (values[i] < compare) return i;
       }
       return -1; // to show none found
    }
    
  • -1
  • The method will only return -1 if no value in the array is less than the passed value.
  • -15
  • The method returns the index of the first item in the array that is less than the value, not the value.
  • 1
  • Since the method loops from the back towards the front -15 is the last value in the array that is less than -13 and it is at index 1.
  • You will get an out of bounds error.
  • No, the method correctly starts the index at values.length - 1 and continues as long as i is greater than or equal to 0.

    6-2-3: Given the following code segment what will be returned when you execute: getIndexLastSmaller(7);

    private int[ ] values = {-20, -15, 2, 8, 16, 33};
    
    public int getIndexLastSmaller(int compare)
    {
       for (int i = values.length; i >=0; i--)
       {
          if (values[i] < compare) return i;
       }
       return -1; // to show none found
    }
    
  • -1
  • The method will only return -1 if no value in the array is less than the passed value.
  • 1
  • Check the starting index. Is it correct?
  • 2
  • Check the starting index. Is it correct?
  • You will get an out of bounds error.
  • You can not start the index at the length of the array. You must start at the length of the array minus one. This is a common mistake.

6.2.2. Looping through Part of an Array

You don’t have to loop through all of the elements of an array. You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (&&) on line 14 to make sure that the loop doesn’t go beyond the length of the array, because if you had an array that had less than 5 elements, you wouldn’t want the code to try to double the 4th element which doesn’t exist!

coding exercise Coding Exercise

You can even start in the middle and loop through the rest of the array. Does this work for arrays that have an even number of elements? Does it work for arrays that have an odd number of elements? Modify the main code below to test with both arrays with an even number of items and an odd number.

exercise Check Your Understanding

    6-2-4: Given the following values of a and the method doubleLast what will the values of a be after you execute: doubleLast()?

    private int[ ] a = {-20, -15, 2, 8, 16, 33};
    
    public void doubleLast()
    {
    
       for (int i = a.length / 2; i < a.length; i++)
       {
          a[i] = a[i] * 2;
       }
    }
    
  • {-40, -30, 4, 16, 32, 66}
  • This would true if it looped through the whole array. Does it?
  • {-40, -30, 4, 8, 16, 32}
  • This would be true if it looped from the beginning to the middle. Does it?
  • {-20, -15, 2, 16, 32, 66}
  • It loops from the middle to the end doubling each value. Since there are 6 elements it will start at index 3.
  • {-20, -15, 2, 8, 16, 33}
  • This would be true if array elements didn't change, but they do.

    6-2-5: Given the following values of a and the method mystery what will the values of a be after you execute: mystery()?

    private int[ ] a = {-20, -15, 2, 8, 16, 33};
    
    public void mystery()
    {
    
       for (int i = 0; i < a.length/2; i+=2)
       {
          a[i] = a[i] * 2;
       }
    }
    
  • {-40, -30, 4, 16, 32, 66}
  • This would true if it looped through the whole array and doubled each. Does it?
  • {-40, -30, 4, 8, 16, 33}
  • This would be true if it looped from the beginning to the middle and doubled each. Does it?
  • {-20, -15, 2, 16, 32, 66}
  • This would be true if it looped from the middle to the end and doubled each. Does it?
  • {-40, -15, 4, 8, 16, 33}
  • This loops from the beginning to the middle and doubles every other element (i+=2 is the same as i = i + 2).
  • {-40, -15, 4, 8, 32, 33}
  • This would be true if it looped through the whole array and doubled every other element. Does it?
        6-2-6: The following program has the correct code to reverse the elements in an array, a,  but the code is mixed up.  Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.

public void reverse() { --- int temp = 0; int half = a.length / 2; int max = a.length - 1; for (int i = 0; i < half; i++) { --- temp = a[i]; --- a[i] = a[max - i]; --- a[max - i] = temp; --- } // end for --- } // end method
        6-2-7: The following program has the correct code to return the average of the first 3 items in the array a, but the code is mixed up.  Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.

public double avg3() { --- double total = 0; for (int i = 0; i < a.length && i < 3; i++) { --- total = total + a[i]; --- } // end for return total / 3; --- } // end method

6.2.3. Things to Watch For When Looping Through an Array

When processing all array elements be careful to start at the first index which is 0 and end at the last index which is arrayName.length - 1. Be careful not to go past the bounds of the array which means don’t use a negative number as an index or a number that is equal to or greater than the length of the 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.

coding exercise Coding Exercise

The following code has an ArrayIndexOutOfBoundsException. It has 2 common off-by-one errors in the loop. Can you fix it and make the loop print out all the scores?

Also, be careful not to jump out of loop too early when you are looking for a value in an array. The method below uses return statements to stop the execution of the method and return a value to the method that called this method. If a return statement returns a value, the type of that value must match the return type in the method header. Methods with a return type of void can’t return any values, but can have one or more return statements to stop the execution of the method and return to the calling method.

coding exercise Coding Exercise

What is wrong with the code below? The first time through the loop it will start with the element at index 0 and check if the item at the array index equals the passed target string. If they have the same characters in the same order it will return 0, otherwise it will return -1. But, it has only processed one element of the array. How would you fix the code to work correctly (process all array elements before returning)?

6.2.4. groupwork Programming Challenge : SpellChecker

Spell Checker

We encourage you to work in pairs for this challenge. Make sure you have done the last coding exercise above which will help you with this challenge.

The following Active Code uses a dictionary array of the most common 100 English words. We can use it as a spelling checker! For a more realistic application, you may want to use this repl.it code instead that has a huge dictionary of English words read in from a file and lets you do input with your spell checker. If you use repl, copy in the link for your repl in the Active Code window below to turn it in.

  1. Write a print10() method that prints out the first 10 words of the dictionary array.

  2. Write a spellcheck() method that takes a word as a parameter and returns true if it is in the dictionary array. It should return false if it is not found. Test your code below by changing the word sent to the spellcheck() method in main. This algorithm is called a linear search where we step through the array one element at a time (here the dictionary one word at a time) looking for a certain element.

3. Write a method printStartsWith(String) that prints out the words that start with a String of letters in the dictionary array. Your method should take a parameter for the firstLetters as a String. You could use the Java String startsWith() method here if you’d like to, or use indexOf() to see if the firstLetters is at index 0 of the string.

6.2.5. 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.

You have attempted of activities on this page
Next Section - 6.3. Enhanced For-Loop (For-Each) for Arrays