Row Sum and Column Sum of a Matrix in C

Row Sum and Column Sum of a Matrix in C. Previously we had developed multiple C program on matrix like C program to find the Addition of two Matrix, C program to find subtraction of two matrices, C Program to Find Multiplication of two Matrix, C program to Find Transpose of a Matrix, Sum of diagonal elements in C. Now let us develop a simple program to find the row sum and column sum of a matrix.

matrix
#include<stdio.h>
// function to find and display 
// row and column sum of a 3x3 matrix
void sum(int m[3][3])
{
  int rowsum, columnsum;

  for(int i=0; i<3; i++)
  {
    rowsum = 0;
    columnsum = 0;

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

    printf("Sum of row %d = %d,\t", i, rowsum);
    printf("Sum of Column %d = %d\n", i, columnsum);
  }
}

// function to display 3x3 matrix
void display(int matrix[3][3])
{
  for(int i=0; i<3; i++)
  {
    for(int j=0; j<3; j++)
      printf("%d\t",matrix[i][j]);

    printf("\n"); // new line
  }
}

// main function
int main()
{
  // take a 3x3 matrix
  int a[][3] = { {1,2,3}, {4,5,6}, {7,8,9} };

  // print matrix
  printf("Entered matrix is:\n");
  display(a);

  // find row sum and column sum
  sum(a); 

  return 0;
}

Output:-

Entered matrix is:
1 2 3
4 5 6
7 8 9
Sum of row 0 = 6, Sum of Column 0 = 12
Sum of row 1 = 15, Sum of Column 1 = 15
Sum of row 2 = 24, Sum of Column 2 = 18

In this matrix operations program, we had written logic in C programming to find the sum of each column, and the sum of each row. First, we had taken a matrix and then displayed it on the screen. After that sum of columns and the sum of rows is calculated and displayed.

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 Comment

Your email address will not be published. Required fields are marked *