How to get the sum of every row in a given matrix
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, and3. - The second row in the output, (
15) indicates the sum of the elements of the second row, i.e.,4,5, and6. - The third row in the output, (
24) indicates the sum of the elements of the third row, i.e.,7,8, and9.
Algorithm
- 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. - Iterate through every row of the matrix and execute the following:
- Initialize a sum variable to zero.
- Loop through all the elements in the row.
- Add every element to the sum variable.
- Add the sum variable to the
rowSumarray defined in Step 1 of the algorithm.
- Return the
rowSumarray.
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