Java Program to find Sum of each Matrix Column

Write a Java Program to find Sum of each Matrix Column with an example. Or Java Program to calculate sum of each and every column in a given Multi-dimensional array or Matrix.

In this Java Matrix column sum example, we declared a 3 * 3 integer SumOfCols_arr matrix with random values. Next, we used for loop to iterate the SumOfCols_arr Matrix items. Within the for loop, we are calculating the sum of Matrix columns.

public class SumOfMatrixColumns {
	
	public static void main(String[] args) {
		
		int i, j, sum;	
	
		int[][] SumOfCols_arr = {{11, 21, 31}, {41, 51, 61}, {71, 81, 91}};
	
		
		for(i = 0; i < SumOfCols_arr.length; i++)
		{
			sum = 0;
			for(j = 0; j < SumOfCols_arr[0].length; j++)
			{
				sum = sum + SumOfCols_arr[j][i];
			}
			System.out.println("\nThe Sum of Matrix Items "
					+ "in Column " + i + " = " + sum);
		}
	}
}
Java Program to find Sum of each Matrix Column 1

Java Program to find Sum of each Matrix Column example 2

This Java code for Matrix sum of each column is the same as the above. However, this Java sum of matrix column code allows the user to enter the number of rows, columns, and the matrix items. Please refer to C Program to find the Sum of each Column in a Matrix article to understand the iteration-wise for loop execution.

import java.util.Scanner;

public class SumOfMatrixColumns {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int i, j, rows, columns, sum = 0;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Enter Matrix Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] SumOfCols_arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				SumOfCols_arr[i][j] = sc.nextInt();
			}		
		}	

		for(i = 0; i < SumOfCols_arr.length; i++)
		{
			sum = 0;
			for(j = 0; j < SumOfCols_arr[0].length; j++)
			{
				sum = sum + SumOfCols_arr[j][i];
			}
			System.out.println("\nThe Sum of Matrix Items "
					+ "in Column " + i + " = " + sum);
		}
	}
}

Java Matrix columns output

 Enter Matrix Rows and Columns :  
3 3

 Please Enter the Matrix Items :  
10 20 30
12 22 33
130 40 50

The Sum of Matrix Items in Column 0 = 152

The Sum of Matrix Items in Column 1 = 82

The Sum of Matrix Items in Column 2 = 113