In computer programming, the for each loop is called enhanced for each loop.
It is the shorter version of the traditional for loop used in computer programming.
The enhanced for loop is written as shown.
For ( data type variable : array_name )
{
code of the loop goes here
}
An example of integer array using enhanced for loop is shown below. The Java code is given below.
1. First, an integer array is declared and initialized simultaneously. Hence, the size of the array is not known explicitly and no index variable is needed.
2. Next, an integer variable is initialized which iterates over every element of the array.
3. The variable which holds the element of the array is displayed.
int[] tens = { 10, 20, 30, 40, 50, 60, 70, 80, 90 } ;
for ( int t : tens )
{
System.out.println( t );
}
a. The above code does not include any index variable. The enhanced loop can only be used to traverse the given array.
The array can only be traversed in forward direction, i.e., elements of the array can only be traversed beginning from the first element to the last.
By default, enhanced for loop traversal begins from index 0 of the array to the last index of the array. This needs the index variable to be coded.
Also, index variable gives traditional for loop more control on how the elements can be traversed and which elements to be traversed.
b. The for each loop can not always be re written as for loop. The for loop is used when more just element traversal is needed.
c. The for each loop executes only till the variable traverses through all the elements of the array. The loop terminates when all the elements are visited. Thus, ArrayIndexOutOfBoundsException can not be thrown by the enhanced for loop.