Related Tags

communitycreator
algorithm
java

# How to get the sum of every column in a given matrix

abhilash

### 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, and 7.
• The second row in the output, (15) indicates the sum of the elements of the second column, i.e., 2, 5, and 8.
• The third row in the output, (18) indicates the sum of the elements of the third column, i.e., 3, 6, and 9.

### Algorithm

1. 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.

2. Iterate through every column of the matrix and execute the following:

1. Initialize a sum variable to zero.
2. Loop through all the elements in the column.
3. Add every element to the sum variable.
4. Add the sum variable to the colSum array defined in Step 1 of the algorithm.
3. Return the colSum array.

### Complexity

• Time complexity - $O(N^2)$
• Space complexity - $O(N)$

### 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 columns
for(int i = 0; i < numCols; i++)
{
// define the sum variable to get the column sum
int sum = 0;

// Loop through the elements in the column
for(int j = 0; j < numRows; j++)
// add every element to the sum variable
sum += matrix[j][i];
// add the column sum to the result array
colSum[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);
}
}

RELATED TAGS

communitycreator
algorithm
java

CONTRIBUTOR

abhilash
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time