Tag Archives: Java 5

Enhanced for loop

Many times it happens that we have to iterate through an entire array. Java 1.5 and above provides a special construct for these cases known as enhanced for statement or enhanced for loop. The original intended purpose of the enhanced for wasΒ to iterate through all the elements of a Collection. Collections are outside the scope of the ICSE and ISC syllabus. In this post I will demonstrate the use of enhanced for loop for iterating in case of an array.

I will use the same program which I used in my previous post on “Creating variable argument function in Java”. The program given in my previous post was as follows:

class VariableArgumentFunction{
    public static float average( float ... a ){
        float sum=0f;
        for( int i =0 ; i < a.length ; i++ ){
            sum += a[ i ];
        }
        return sum/a.length;
    }
    public static void main(String [] args){
        System.out.println( "Average of 1,2 is " + average( 1, 2 ) );
        System.out.println( "Average of 1,2,3 is " + average( 1, 2, 3 ) );
        System.out.println( "Average of 1,2,3,4 is " + average( 1, 2, 3, 4 ) );
    }
}

In the above program the for loop in the function average is iterating for the entire array. The program using enhanced for after changing the name of the class is as follows:

class EnhancedForLoop{
    public static float average( float ... a ){
        float sum=0f;
        for( float n: a ){
            sum += n;
        }
        return sum/a.length;
    }
    public static void main(String [] args){
        System.out.println( "Average of 1,2 is " + average( 1, 2 ) );
        System.out.println( "Average of 1,2,3 is " + average( 1, 2, 3 ) );
        System.out.println( "Average of 1,2,3,4 is " + average( 1, 2, 3, 4 ) );
    }
}

Notice line number 4 in the above program. The enhanced for loop in declaring a variable f which would assume each value if an array one by one. The body of the loop would also change so as to use this value which stored in the variable n. Thus we see that enhanced for loop provides us with a concise way to iterate through the entire loop, however, it’s only useful if the entire array is to be iterated.