For-Each Loop
The for-each loop is a simplified version of the for loop that enables you to iterate over the elements of a collection or array without needing to manage an index variable.
Apprentice · Java · Updated
The for-each loop is a simplified version of the for loop that enables you to iterate over the elements of a collection or array without needing to manage an index variable.
Example
This example loops through the same array of names, but it uses a for-each loop instead of a basic for loop.
public class ForEachLoopExample
{
public static void main(String[] args)
{
String[] names = {"Alice", "Bob", "Charlie"};
// this reads as for each name in the names array
for (String name : names)
{
System.out.println(name);
}
}
}
In this for-each example, the loop automatically iterates over each element in the names array. As the loop progresses it assigns the current element to the variable name during each iteration. This loop is both more readable and less error-prone for this use case.
Do it: find the cheapest item on the menu
The deli wants to put "Meals from $…" on its sign, so it needs the lowest price on its menu.
The function gets one value:
prices: every price on the menu, adouble[]. It always holds at least one price.
For example:
double[] prices = {8.50, 6.25, 11.00, 7.75};
Start with the first price as the lowest so far, then look at each price in turn:
| Price | Lower than the lowest so far? | Lowest so far |
|---|---|---|
| (start) | $8.50 | |
| $8.50 | No | $8.50 |
| $6.25 | Yes | $6.25 |
| $11.00 | No | $6.25 |
| $7.75 | No | $6.25 |
So lowestPrice(prices) returns 6.25.
Your job: write the function double lowestPrice(double[] prices) with a for-each loop.
- Return the lowest price in the array.
- When two items share the lowest price, return that price.
- With only one price, return it.
Practiced live on the lesson page: write the Java right there and check it.