Java Online Compiler
Example: SumElementsEnhancedForLoop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// SumElementsEnhancedForLoop public class Main { public static void main(String[] args) { // Step 1: Define the 2D array int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Step 2: Initialize a variable to store the sum int sum = 0; // Step 3: Iterate through each row in the 2D array for (int[] row : matrix) { // Step 4: Iterate through each element in the current row for (int element : row) { // Step 5: Add the current element to the sum sum += element; } } // Step 6: Print the total sum System.out.println("Sum of all elements (Enhanced For Loop): " + sum); } }
Output
Clear
ADVERTISEMENTS