Common Array Algorithms

This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.

14. Enhanced for loop


Answer:

The index j goes one cell too far. An ArrayIndexOutOfBoundsException will be thrown and you program will be halted.

Off-by-one errors are very common. A running Java program checks each array index before it is used to be sure it is within bounds.

Enhanced for loop

class MaxAlgorithm
{
  public static void main ( String[] args ) 
  {

    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   max;

    // initialize the current maximum
    max = array[0];

    // scan the array
    for ( int value : array )
    { 
      if ( value > max )    // examine the current element
        max = value ;         // if it is the largest so far, change max
    }
      
    System.out.println("The maximum of this array is: " + max );
  }
}


Java has an enhanced for loop that visits each element of an array in order. It automatically avoids off-by-one bugs. Study the program (above). The program does the same thing as the previous program, but with different syntax.

(There is a colon : separating value and array in the above. This might be hard to see in your browser.)

To read this code out loud say: "For each value in array, ..."

Sometimes the enhanced for loop is called a foreach loop.

The enhanced for loop

for ( int value : array )
{
}

assigns to value the contents of each cell of the array starting with cell zero and going in order up to the last cell of the array. For each assignment, the loop body is executed. With this enhanced for loop there is no danger of an index that might go out of bounds, nor any danger of skipping the first or last element.

Question 14:

Must the enhanced for loop start with the first (index 0) element of the array?