For Each

As you have probably realised by now, the standard for loop, whilst powerful, is a little unwieldy. An alternative method of iteration a foreach loop can be used in some, limited, circumstances. Typically if we have an array we want to iterate through, but not amend the contents of, an Array.

The structure of a foreach loop is as follows

for (TypeOfData nameOfVariable : nameOfArray) {
    //do something with nameOfVariable
}

The next example shows two loops, a standard for loop and the equivalent as a foreach loop:

//for loop
for (int i = 0; i < weekDays.length; i++) {
    String day = weekDays[i];
    System.out.println(day);
}

//foreach loop
for (String day : weekDays) {
    System.out.println(day);
}

As you can see the syntax is more succinct, and we avoid possible errors with going out of the bounds of the array that we can experience if we get the for loop syntax wrong. On the downside, we do not know the index of the position of an item in the array, and we cannot change it (changing the 'day' variable in the above example would not change the value stored in the array, only the value of the variable for that iteration of the loop)

Task

  1. In a new command line project, rewrite the following code as a foreach loop and test it:
    String[] words = {"the", "cat", "sat", "on", "the", "mat"};
    String phrase = "";
    for (int i = 0; i < words.length ; i++) {
        phrase += words[i] + " ";
    }
    System.out.println(phrase.trim());
  2. In the above project rewrite the following code as a foreach loop:
    double total = 0;
    double[] hourlyTemperatures = {13.5,14.5,15.0,15.5,16.0,16.5,17.0,17.5,17.0,16.0,15.0,14.0};
    for (int i = 0; i < hourlyTemperatures.length; i++) {
        total += hourlyTemperatures[i];
    }
    double average = total / hourlyTemperatures.length;
    System.out.println(average);
  3. Revisit your previous tasks, and where appropriate, replace 'for' loops with 'foreach' loops, and test your work. Remember not all loops can be replaced, particularly when the loop modifies the array it is iterating over