Row Sum and Column Sum of Matrix in Java

Program description:- Write a Java program to find the sum of each row and the sum of each column in a given matrix. Display the resultant values.

Example:-
Matrix =
20 19 18
17 16 15
14 13 12
Row-1 sum = 20+19+18 = 57
Column-1 sum = 20+17+14 = 51
Row-2 sum = 17+16+15 = 48
Column-2 sum = 19+16+13 = 48
Row-3 sum = 14+13+12 = 39
Column-3 sum = 18+15+12 = 45

Before solving this problem, you should have knowledge of how to declare and initialize a matrix in Java, how to take input for a matrix from the end-user, and what are the different ways to display it. How to find the length or size of a matrix in Java? How to pass and return a matrix in Java. See:- Matrix in Java

matrix

Java Program to Find the Sum of Row and Sum of Column in Matrix

import java.util.Scanner;

public class Matrix {

  // main method
  public static void main(String[] args) {

    // declare variables
    int row = 0;
    int column = 0;
    int a[][] = null; // matrix
    
    // create Scanner class object to read input
    Scanner scan = new Scanner(System.in);

    // ask row and column size
    System.out.println("Enter row and column size: ");
    row = scan.nextInt();
    column = scan.nextInt();

    // initialize matrices
    a = new int[row][column];

    // read matrix A
    System.out.println("Enter Matrix: ");
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a[0].length; j++) {
        a[i][j] = scan.nextInt();
      }
    }

    // variables
    int rowsum;
    int columnsum;

    // find row sum and column sum
    for (int i = 0; i < 3; i++) {

      rowsum = 0;
      columnsum = 0;

      for (int j = 0; j < 3; j++) {
        rowsum += a[i][j];
        columnsum += a[j][i];
      }

      System.out.println("Row-" + (i + 1) + " sum = " + rowsum);
      System.out.println("Column-" + (i + 1) + " sum = " + columnsum);
    }
    
    // close Scanner
    scan.close();
  }

}

Output:-

Enter row and column size:
3 3
Enter Matrix:
20 19 18
17 16 15
14 13 12
Row-1 sum = 57
Column-1 sum = 51
Row-2 sum = 48
Column-2 sum = 48
Row-3 sum = 39
Column-3 sum = 45

Enter row and column size:
3 3
Enter Matrix:
1 2 3
4 5 6
7 8 9
Row-1 sum = 6
Column-1 sum = 12
Row-2 sum = 15
Column-2 sum = 15
Row-3 sum = 24
Column-3 sum = 18

See more matrix programs in Java:- 

  1. Program to Print 3×3 Matrix 
  2. Sum of matrix elements in Java
  3. Sum of Diagonal Elements of Matrix in Java 
  4. Matrix Addition in Java
  5. Subtraction of two matrices in Java 
  6. Transpose of a Matrix in Java 
  7. Matrix Multiplication in Java
  8. Menu-driven program for Matrix operations

Also See:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply