Column Sum of Matrix

This program calculates the sum of each column in a matrix.

Problem Statement

Write a Java program to calculate the sum of each column in a 3x3 matrix.

Source Code

1 public class MatrixColumnSum {
2 public static void main(String[] args) {
3 int[][] A = {{1,2,3},{4,5,6},{7,8,9}};
4 for(int j=0;j<3;j++){
5 int sum=0;
6 for(int i=0;i<3;i++){
7 sum+=A[i][j];
8 }
9 System.out.println("Sum of column "+j+": "+sum);
10 }
11 }
12 }

Program Output

Sum of column 0: 12
Sum of column 1: 15
Sum of column 2: 18

Explanation

The outer loop iterates through columns and the inner loop adds all elements of each column into a local sum, demonstrating how multidimensional arrays can be processed column by column.

Quick Links to Explore