It Elective Module
It Elective Module
INTRODUCTION
Java for-each Loop or Enhanced for Loop provides an alternative approach to traverse
the array or collection in Java. It is mainly used to traverse the array or collection elements.
The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the
code more readable. It is known as the for-each loop because it traverses each element one
by one.
The drawback of the for-each loop is that it cannot traverse the elements in reverse
order. Here, you do not have the option to skip any element because it does not work on an
index basis. Moreover, you cannot traverse the odd or even elements only.
What are the Advantages for-each or enhance loop over for loop?
Syntax
The syntax of Java for-each loop consists of data_type with the variable followed by a colon
(:), then array or collection.
Output:
3
9
5
-5
We have used the for-each loop to print each element of the numbers array one by one.
1. In the first iteration, the item will be 3.
2. In the second iteration, the item will be 9.
3. In the third iteration, the item will be 5.
4. In the fourth iteration, the item will be -5.
Example #2: A program that will print the Sum of Array Elements
Output:
Sum = 19
the execution of the for each loop looks as:
Iteration Variables
1 numbers = 3
sum = 0 + 3 = 3
2 numbers = 4
sum = 3 + 4 = 7
3 numbers = 5
sum = 7 + 5 = 12
4 numbers = -5
sum = 12 + (-5) = 7
5 numbers = 0
sum = 7 + 0 = 7
6 numbers = 12
sum = 7 + 12 = 19
As we can see, we have added each element of the numbers array to the sum variable in
each iteration of the loop.
Output:
Volvo
BMW
Ford
Mazda
Output:
The sum of elements is: 83
Generalization:
Name: Score:
Year & Section:
Declare an array AGES of 10 elements of type int with the following values 15, 18, 16,
17, 14, 12, 13, 20, 22, 25. Display the average age of a group of people using for-each or
enhance loop.
Expected Output: