In the previous lesson you learnt how you can use loops to cycle through arrays. There is a loop called enhanced for loop which is used to traverse the elements of the array.
The syntax of enhanced for loop goes something like this:

DataType arrayName;
//initialize the array
for (DataType temporaryVariable : arrayName)
{
/*
The temporaryVariable will contain each element of the array during a loop cycle
*/
}

The syntax is confusing. An example will help us understand better.
The following program creates an array and initializes it. Then all the elements are displayed on the screen.

This method is used to retrieve elements from the array. Do not store elements in the array using enhanced for loop.

Now let's consider another example in which we will access the elements of a String array using enhanced for loop.

Now let's use enhanced for loop to sum the elements of an array.

Let's take another example. In this example, we will find the greatest number in an int array.


Practice Corner:

  • Write a program to input some numbers from the user and display the greatest number on the screen.
  • Write a program to input some numbers from the user and display the smallest one on the screen