Sep 30, 2011

C program: Sum Of Elements In A Matrix

Write a C program to read a matrix A (MxN) and to find the following using functions
a) Sum of the elements of each row
b) Sum of the elements of each column
c) Find the sum of all the elements of the matrix
Output the computed results with suitable headings.
Read more about C Programming Language .
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                   Happy Coding
***********************************************************/


#include <stdio.h>
#include <conio.h>

void main()
{
 int arr[10][10];
 int i, j, row, col, rowsum, colsum,sumall=0;

 /* Function declaration */
 int Addrow(int A[10][10], int k, int c);
 int Addcol(int A[10][10], int k, int c);

 clrscr();

 printf("Enter the order of the matrix\n");
 scanf("%d %d", &row, &col);

 printf("Enter the elements of the matrix\n");
 for(i=0; i<row; i++)
 {
  for(j=0; j< col; j++)
  {
   scanf("%d", &arr[i][j]);
  }
 }

 printf("Input matrix is\n");
 for(i=0; i<row; i++)
 {
  for(j=0;j<col;j++)
  {
   printf("%3d", arr[i][j]);
  }
  printf("\n");
 }

 /* computing row sum */
 for(i=0; i<row; i++)
 {
  rowsum = Addrow(arr,i,col);
  printf("Sum of row %d = %d\n", i+1, rowsum);
 }

 for(j=0; j<col; j++)
 {
  colsum = Addcol(arr,j,row);
  printf("Sum of column  %d = %d\n", j+1, colsum);
 }

 /* computation of all elements */
 for(j=0; j< row; j++)
 {
  sumall = sumall + Addrow(arr,j,col);
 } 

 printf("Sum of all elements of matrix = %d\n", sumall);

}

/* Function to add each row */
int Addrow(int A[10][10], int k, int c)
{
 int rsum=0, i;
 for(i=0; i< c; i++)
 {
  rsum = rsum + A[k][i];
 }
 return(rsum);
}

/* Function to add each column */
int Addcol(int A[10][10], int k, int r)
{
 int csum=0, j;
 for(j=0; j< r; j++)
 {
  csum = csum + A[j][k];
 }
 return(csum);
}
Read more Similar C Programs
Matrix Programs
Learn C Programming
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!