πŸ““6.3: Arrays & For-Each Loops

Table of Contents


πŸ“– This page is a condensed version of CSAwesome Topic 6.3


Traversing Arrays with For-Each Loops

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. This type of loop can only be used with arrays and some other collections of items like ArrayLists which we will see in the next unit.

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

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, don’t need to know their index, and don’t need to change their values. It automatically starts by β€œvisiting” the first item in the array (the one at index 0) and continues through, in order, to the last item in the array.

See the examples below in Java that loop through both an int and a String 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 );
  }

Add another high score and another name to the arrays and run again!

For-Each Loop Limitations

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 temporary variable in the loop changes, not the real array values. We would need an indexed loop to modify array elements. Try this code in the Java Visualizer and step through the code to see why it doesn’t work.

Enhanced for-each loops CANNOT be used in all situations! Only use for-each loops when you want to loop through all the values in an array, without changing their values.

  • 🚫 Do not use for-each loops if you need to keep track of the index.
  • 🚫 Do not use for-each loops if you need to change values in the array.
  • 🚫 Do not use for-each loops if you want to loop through only part of an array or in a different order.

πŸ’» In-Class Activity:

  1. Go to
  2. Make sure you SIGN IN!
  3. Complete the Programming Challenge: SpellChecker 2 activity in pairs.

⭐️ 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.


Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.