Java Program to find the sum of each row and each column of a matrix

In this program, we need to calculate the sum of elements in each row and each column of the given matrix.

Java Program to find the sum of each row and each column of a matrix

Above diagram shows the sum of elements of each row and each column of a matrix.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE rows, cols, sumRow, sumCol
  • STEP 3: INITIALIZE matrix a[][] ={{1, 2, 3},{4, 5, 6}, {7, 8, 9}}
  • STEP 4: rows = a.length
  • STEP 5: cols = a[0].length
  • STEP 6: REPEAT STEP 7 to STEP 10 UNTIL i<rows
            // for(i=0; i<rows; i++)
  • STEP 7: SET sumRow =0
  • STEP 8: REPEAT STEP 9 UNTIL j<cols
  • STEP 9: sumRow = sumRow + a[i][j]
  • STEP 10: PRINT i+1, sumRow
  • STEP 11: REPEAT STEP 12 to STEP 15 UNTIL i<cols
            //for(i=0; i<cols; i++)
  • STEP 12: SET sumCol =0
  • STEP 13: REPEAT STEP 14 UNTIL j<rows
            //for(j=0; j<rows; j++)
  • STEP 14: sumCol =sumCol + a[j][i]
  • STEP 15: PRINT i+1, sumCol
  • STEP 16: END

Program

  1. public class SumofRowColumn    
  2. {    
  3.     public static void main(String[] args) {    
  4.         int rows, cols, sumRow, sumCol;    
  5.             
  6.         //Initialize matrix a    
  7.         int a[][] = {       
  8.                         {1, 2, 3},    
  9.                         {4, 5, 6},    
  10.                         {7, 8, 9}    
  11.                     };    
  12.               
  13.           //Calculates number of rows and columns present in given matrix    
  14.           rows = a.length;    
  15.         cols = a[0].length;    
  16.             
  17.         //Calculates sum of each row of given matrix    
  18.         for(int i = 0; i < rows; i++){    
  19.             sumRow = 0;    
  20.             for(int j = 0; j < cols; j++){    
  21.               sumRow = sumRow + a[i][j];    
  22.             }    
  23.             System.out.println(“Sum of ” + (i+1) +” row: ” + sumRow);    
  24.         }    
  25.             
  26.         //Calculates sum of each column of given matrix    
  27.         for(int i = 0; i < cols; i++){    
  28.             sumCol = 0;    
  29.             for(int j = 0; j < rows; j++){    
  30.               sumCol = sumCol + a[j][i];    
  31.             }    
  32.             System.out.println(“Sum of ” + (i+1) +” column: ” + sumCol);    
  33.         }    
  34.     }    
  35. }    

Output:

Sum of 1 row: 6
Sum of 2 row: 15
Sum of 3 row: 24
Sum of 1 column: 12
Sum of 2 column: 15
Sum of 3 column: 18

Leave a Comment