Java Online Compiler
Example: SumElementsNestedForLoop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// SumElementsNestedForLoop 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 of the 2D array for (int i = 0; i < matrix.length; i++) { // Step 4: Iterate through each element in the current row for (int j = 0; j < matrix[i].length; j++) { // Step 5: Add the current element to the sum sum += matrix[i][j]; } } // Step 6: Print the total sum System.out.println("Sum of all elements (Nested For Loop): " + sum); } }
Output
Clear
ADVERTISEMENTS