How to get the sum of every column in a given matrix
Problem overview
Given a matrix, print the sum of the column elements in the matrix.
For example, consider the matrix below.
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
The column sum of the matrix above is as follows.
12
15
18
Explanation
- The first row in the output, (
12) indicates the sum of the elements of the first column, i.e.,1,4, and7. - The second row in the output, (
15) indicates the sum of the elements of the second column, i.e.,2,5, and8. - The third row in the output, (
18) indicates the sum of the elements of the third column, i.e.,3,6, and9.
Algorithm
-
Create an array of size equal to the number of columns. This array is used to store the column sum of every column. Let the array be
colSum. -
Iterate through every column of the matrix and execute the following:
- Initialize a sum variable to zero.
- Loop through all the elements in the column.
- Add every element to the sum variable.
- Add the sum variable to the
colSumarray defined in Step 1 of the algorithm.
-
Return the
colSumarray.
Complexity
- Time complexity -
- Space complexity -
Code
import java.util.Arrays;public class Main{private static int[] printColSum(int[][] matrix){int numRows = matrix.length;int numCols = matrix[0].length;int[] colSum = new int[numCols];// Loop through the given number of columnsfor(int i = 0; i < numCols; i++){// define the sum variable to get the column sumint sum = 0;// Loop through the elements in the columnfor(int j = 0; j < numRows; j++)// add every element to the sum variablesum += matrix[j][i];// add the column sum to the result arraycolSum[i] = sum;}return colSum;}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 column sum of the above matrix is as follows:");int[] colSum = printColSum(matrix);for(int i: colSum)System.out.println(i);}}