In this lesson, you will learn
for (elementType elementVariable : arrayOrCollection) {
// Code to be executed for each element
// elementVariable holds the current element's value
}
elementType: The data type of the elements in the array or collection.elementVariable: A variable that will hold the value of each element during each iteration.arrayOrCollection: The array or collection you want to iterate over.
public class ForEach1DArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Elements of the array:");
for (int number : numbers) {
System.out.println(number);
}
// Example of summing the elements
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("Sum of the elements: " + sum);
}
}
Elements of the array:
1
2
3
4
5
Sum of the elements: 15
When using a for-each loop with a 2D array, you’ll need nested loops. The outer loop iterates over the rows, and the inner loop iterates over the elements in each row.
public class ForEach2DArray {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Elements of the 2D array:");
for (int[] row : matrix) { // Outer loop: iterates through rows
for (int element : row) { // Inner loop: iterates through elements in each row
System.out.print(element + " ");
}
System.out.println(); // Move to the next line after each row
}
//Example of summing all elements in the 2D array.
int totalSum = 0;
for (int[] row : matrix){
for(int element : row){
totalSum+=element;
}
}
System.out.println("The total sum of all elements is: " + totalSum);
}
}
Elements of the 2D array:
1 2 3
4 5 6
7 8 9
The total sum of all elements is: 45
for loops with indices.
Therefore, to take user input and store it in an array, you’ll need to use a traditional for loop with an index. Here’s a breakdown and example:
Here’s the correct way to do it using a standard for loop:
import java.util.Scanner;
public class ArrayUserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
System.out.println("Enter " + size + " numbers:");
// Use a traditional for loop to take input
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println("Array elements:");
// Now, you can use a for-each loop to display the array
for (int number : numbers) {
System.out.print(number + " ");
}
System.out.println();
scanner.close();
}
}
Enter the size of the array: 5
Enter 5 numbers:
4
5
6
7
8
Array elements:
4 5 6 7 8
There is some overlapping of the content making it bit unreadable. Please verify.
You must be logged in to submit a review.