✏️ Explanatory Question
Write a Java program to calculate and print the sum of all elements in the following 2D array:
int[][] arr = { {2, 4, 6}, {1, 3, 5}, {7, 8, 9} };
Write a Java program to calculate and print the sum of all elements in the following 2D array:
int[][] arr = { {2, 4, 6}, {1, 3, 5}, {7, 8, 9} };
public class Main {
public static void main(String[] args) {
int[][] arr = {
{2, 4, 6},
{1, 3, 5},
{7, 8, 9}
};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
System.out.println("Sum of all elements: " + sum);
}
}