Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matrix
communitycreator

How to get the sum of every row in a given matrix

abhilash

Problem overview

Given a matrix, print the sum of the row elements in the matrix.

For example, consider the matrix below.

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

The row sum of the matrix above is as follows.

6
15
24

Explanation

  • The first row in the output, (6) indicates the sum of the elements of the first row, i.e., 1, 2, and 3.
  • The second row in the output, (15) indicates the sum of the elements of the second row, i.e., 4, 5, and 6.
  • The third row in the output, (24) indicates the sum of the elements of the third row, i.e., 7, 8, and 9.

Algorithm

  1. Create an array of size equal to the number of rows. This array is used to store the row sum of every row. Let the array be rowSum.
  2. Iterate through every row of the matrix and execute the following:
    1. Initialize a sum variable to zero.
    2. Loop through all the elements in the row.
      1. Add every element to the sum variable.
    3. Add the sum variable to the rowSum array defined in Step 1 of the algorithm.
  3. Return the rowSum array.

Complexity

  • Time complexity - O(N*N)
  • Space complexity - O(N)

Code

import java.util.Arrays;

public class Main{

    private static int[] printRowSum(int[][] matrix){
        int numRows = matrix.length;
        int numCols = matrix[0].length;
        int[] rowSum = new int[numRows];
        for(int i = 0; i < numRows; i++)
        {
            int sum = 0;
            for(int j = 0; j < numCols; j++) sum += matrix[i][j];
            rowSum[i] = sum;
        }
        return rowSum;
    }

    private static void printMatrix(int[][] matrix){
        for (int[] row : matrix)
            System.out.println(Arrays.toString(row));
    }

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

        printMatrix(matrix);
        System.out.println("The row sum of the above matrix is as follows:");
        int[] rowSum = printRowSum(matrix);
        for(int i: rowSum)
            System.out.println(i);
    }
}
Row Sum of matrix

RELATED TAGS

matrix
communitycreator
RELATED COURSES

View all Courses

Keep Exploring