6.3. Enhanced For-Loop (For-Each) for Arrays

There is a special kind of loop that can be used with arrays that is called an enhanced for loop or a for each loop. This loop is much easier to write because it does not involve an index variable or the use of the []. It just sets up a variable that is set to each value in the array successively. To set up a for-each loop, use for (type variable : arrayname) where the type is the type for elements in the array, and read it as “for each variable value in arrayname”. You may have used a similar loop in AP CSP Pseudocode or App Inventor with lists like below.

../_images/appinvForEachComparison.png

Figure 2: Comparing App Inventor, AP CSP, and Java for each

See the examples below in Java that loop through an int and a String array. Notice the type of the loop variable is the type of the array.

int[] highScores = { 10, 9, 8, 8};
String[] names = {"Jamal", "Emily", "Destiny", "Mateo"};
// for each loop: for each value in highScores
// for (type variable : arrayname)
for (int value : highScores)
{
    // Notice no index or [ ], just the variable value!
    System.out.println( value );
}
// for each loop with a String array to print each name
// the type for variable name is String!
for (String name : names)
{
    System.out.println(name);
}

Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don’t need to know their index and don’t need to change their values. This type of loop can only be used with collections of items like arrays. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array.

coding exercise Coding Exercise

Try the following code. Notice the for each loop with an int array and a String array. Add another high score and another name to the arrays and run again.

coding exercise Coding Exercise

Rewrite the following for loop which prints out the even numbers in the array as an enhanced for-each loop. Make sure it works!

What if we had a loop that incremented all the elements in the array. Would that work with an enhanced for-each loop? Unfortunately not! Because only the new variable changes, not the real array values. We would need an indexed loop for this to work. Try it in the Java visualizer and click on Forward to see why it doesn’t work.

exercise Check Your Understanding

    6-3-1: What are some of the reasons you would use a for-each loop instead of a for loop?

    I: If you wish to access every element of an array.
    II: If you wish to modify elements of the array.
    III: If you wish to refer to elements through a variable name instead of an array index.
    
  • Only I.
  • This style of loop does access every element of the array, but using a for-each loop also means the user can access elements through the variable name.
  • I and III only.
  • Correct! For-each loops access all elements and enable users to use a variable name to refer to array elements, but do not allow users to modify elements directly.
  • II and III only.
  • For-each loops, as well as allowing users to refer to array elements, run through every element. For-each loops also do not allow users to modify elements directly.
  • All of the Above.
  • For-each loops access all of an array's elements and allow users to refer to elements through a variable, but do not allow users to modify elements directly.

Note

Only use the for-each loop when you want to loop through all the values in an array or list. If you only want to loop through part of an array or list use a for loop instead. Also use a for loop instead of a for-each loop if you want to change any of the values in the array or list.

Here is an object-oriented example that has the array as a private instance variable in the class and provides a public method average that uses a for-each loop. You can use the Java visualizer to step through this code.

exercise Check Your Understanding

        6-3-2: The following method has the correct code to return the largest value in an integer array called vals (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 as well. You will be told if any of the blocks are in the wrong order or not indented correctly.

public int getLargest() { --- int largest = vals[0]; --- for (int item : vals) { --- if (item > largest) { --- largest = item; --- } // end if --- } // end for return largest; --- } // end method

If you want to step through the correct code to see what it does in the Java Visualizer click on the following Java visualizer link.

exercise Check Your Understanding

    6-3-3: Given that a is an array of integers and val is an integer value, which of the following best describes the conditions under which the following code segment will return true?

    boolean temp = false;
    for ( int i = 0; i < a.length; i++)
    {
      temp = ( a[i] == val );
    }
    return temp;
    
  • Whenever the first element in a is equal to val.
  • This would be true if the loop started at the end of the array and moved toward the beginning. But, it will loop from the first element to the last.
  • Whenever a contains any element which equals val.
  • This would be true if temp was only set to the result of checking if the current element in the array is equal to val when it is false. But, it is reset each time through the loop.
  • Whenever the last element in a is equal to val.
  • The variable temp is assigned to the result of checking if the current element in the array is equal to val. The last time through the loop it will check if the last element is equal to val.
  • Whenever only 1 element in a is equal to val.
  • There is no count of the number of times the array element is equal to val.

    6-3-4: Given the following field and method, which of the following best describes the contents of myStuff after (int m = mystery(n);) has been executed?

    // private field in the class
    private int[ ] myStuff;
    
    //precondition: myStuff contains
    //  integers in no particular order
    public int mystery(int num)
    {
       for (int k = myStuff.length - 1; k >= 0; k--)
       {
           if (myStuff[k] < num)
           {
              return k;
           }
       }
    
       return -1;
     }
    
  • All values in positions m+1 through myStuff.length-1 are greater than or equal to n.
  • Mystery steps backwards through the array until the first value less than the passed num (n) is found and then it returns the index where this value is found.
  • All values in position 0 through m are less than n.
  • This would be true if mystery looped forward through the array and returned when it found a value greater than the passed num (n).
  • All values in position m+1 through myStuff.length-1 are less than n.
  • This would be true if it returned when it found a value at the current index that was greater than num (n).
  • The smallest value is at position m.
  • It returns the first time the condition is met so nothing is known about the values which are unchecked.

    6-3-5: Given the following code segment, which of the following will cause an infinite loop? Assume that temp is an int variable initialized to be greater than zero and that a is an array of integers.

    for ( int k = 0; k < a.length; k++ )
    {
       while ( a[ k ] < temp )
       {
          a[ k ] *= 2;
       }
    }
    
  • The values don't matter this will always cause an infinite loop.
  • An infinite loop will not always occur in this code segment.
  • Whenever a includes a value that is less than or equal to zero.
  • When a contains a value that is less than or equal to zero then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur.
  • Whenever a has values larger then temp.
  • Values larger then temp will not cause an infinite loop.
  • When all values in a are larger than temp.
  • Values larger then temp will not cause an infinite loop.
  • Whenever a includes a value equal to temp.
  • Values equal to temp will not cause the infinite loop.

6.3.1. groupwork Programming Challenge : SpellChecker 2

Spell Checker

Copy the code you used in the Spell Checker Challenge in the last lesson. Re-write the spellcheck(word), and printStartsWith(firstLetters) methods to use enhanced for-each loops instead of indexed for-loops.

6.3.2. Summary

  • An enhanced for loop, also called a for each loop, can be used to loop through an array without using an index variable.

  • An enhanced for loop header includes a variable, referred to as the enhanced for loop variable, that holds each value in the array.

  • For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.

  • Assigning a new value to the enhanced for loop variable does not change the value stored in the array.

  • Program code written using an enhanced for loop to traverse and access elements in an array can be rewritten using an indexed for loop or a while loop.

You have attempted of activities on this page
Next Section - 6.4. Array Algorithms (FRQs)