Java For-each or Enhanced For Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for a loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns elements one by one in the defined variable.
for(Type var:array){
//code to be executed
//syntax for foreach loop
}
public class ForEachDemo
{
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4 };
for (int i : arr)
{
System.out.println(i);
}
}
}
1
2
3
4
//PROGRAM TO PRINT ARRAY VALUES WITH SCANNER
import java.util.Scanner;
public class ForEachDemo
{
public static void main(String arng[]) {
int value[] = new int[5];
Scanner data = new Scanner(System.in);
float sum = 0;
System.out.println("Enter 5 element of array");
// Enhanced for loop
for (int i : value) {
i = data.nextInt();
sum = sum + i;
}
System.out.println("Sum is " +sum);
}
}
Enter 5 element of array
5
5
5
5
5
Sum is 25.0
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning