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}
};

Single Choice
Views 53

Answer:


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);
    }
}

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.