How to find the total sum of matrix rows in Java

2 Answers

0 votes
class Program {
    public static void main(String[] args) {
        int[][] arr = {
            {1, 2, 3, 5},
            {4, 5, 6, 1},
            {7, 8, 9, 3}
        };

        int rows = arr.length;
        int cols = arr[0].length;
        
        int total = 0;
        
        for (int i = 0; i < rows; i++) {
            int sumRow = 0;
            for (int j = 0; j < cols; j++) {
                sumRow += arr[i][j];
            }
            System.out.println("Sum of row " + i + " = " + sumRow);
            total += sumRow;
        }
        
        System.out.println("Total = " + total);
    }
}



/*
run:

Sum of row 0 = 11
Sum of row 1 = 16
Sum of row 2 = 27
Total = 54

*/

 



answered Jun 12, 2024 by avibootz
0 votes
class Program {
    public static int total_sum_of_matrix_rows(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        int total = 0;
        
        for (int i = 0; i < rows; i++) {
            int sumRow = 0;
            
            for (int j = 0; j < cols; j++) {
                sumRow += matrix[i][j];
            }
            
            System.out.println("Sum of row " + i + " = " + sumRow);
            
            total += sumRow;
        }
        
        return total;
    }
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3, 5},
            {4, 5, 6, 1},
            {7, 8, 9, 3}
        };

        System.out.println("Total = " + total_sum_of_matrix_rows(matrix));
    }
}



/*
run:

Sum of row 0 = 11
Sum of row 1 = 16
Sum of row 2 = 27
Total = 54

*/

 



answered Jun 12, 2024 by avibootz

Related questions

2 answers 144 views
1 answer 184 views
184 views asked Apr 17, 2018 by avibootz
2 answers 158 views
1 answer 83 views
...