✏️ Explanatory Question

Write a Java program that calculates the sum of each row in a 2D array and prints the result.

Given the following array:


int[][] arr = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

👁 49 Views
📘 Detailed Answer
🟢 Easy
49
Total Views
8
Related Qs
0%
Progress
💡

Answer with Explanation


public class Main {
    public static void main(String[] args) {
        int[][] arr = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        for (int i = 0; i < arr.length; i++) {
            int rowSum = 0;
            for (int j = 0; j < arr[i].length; j++) {
                rowSum += arr[i][j];
            }
            System.out.println("Row " + (i+1) + " sum: " + rowSum);
        }
    }
}