1.09.2012

Sum of matrix


Q. Write a C program to accept value of matrix and print out the sum of matrix.
OR
Q. Give a example of 2d array with suitable arithmetic operation. 

Ans.

/*program of sum of two matrix*/
#include<stdio.h>
#include<conio.h>
#define MAX 3
void input_mat(int [MAX][MAX], int, int);
void show_mat(int [MAX][MAX], int, int);
void sum_mat(int [MAX][MAX],int [MAX][MAX],int [MAX][MAX],int,int);
int main()
{
 int x[MAX][MAX],y[MAX][MAX],z[MAX][MAX];
 int row,col;
 printf("Enter no. of rows and columns : ");
 scanf("%d%d",&row, &col);
 printf("Enter values in first matrix :\n");
 input_mat(x,row,col);
 printf("Enter values in second matrix :\n");
 input_mat(y,row,col);
 sum_mat(x,y,z,row,col);
 printf("\nDisplay sum of two matrices :");
 show_mat(z,row,col);
 getch();
 return 0;
}


void input_mat(int matA[MAX][MAX], int r, int c)
{
  int i,j;
  for(i=0; i<r; i++)
  {
    for(j=0;j<c; j++)
       scanf("%d",&matA[i][j]);
  }
}


void sum_mat(int matA[MAX][MAX],int matB[MAX][MAX],int matC[MAX][MAX],int r,int c)
{
  int i,j;
  for(i=0; i<r; i++)
  {
    for(j=0;j<c; j++)
       matC[i][j]=matA[i][j]+matB[i][j];
  }
}


void show_mat(int mat[MAX][MAX], int r, int c)
{
  int i,j;
  for(i=0; i<r; i++)
  {
    for(j=0;j<c; j++)
       printf(" %d",mat[i][j]);
    printf("\n");
  }
}


Output:-

Enter no. of rows and columns : 3 3
Enter values in First matrix :
4 5 3
2 1 9
6 7 5
Enter values in second matrix :
1 3 2
7 6 4
2 1 0
Display sum of two matrices :
5 8 5
9 7 13
8 8 5

You might also like:
  1. Difference of two matrix C program
  2. Transpose of matrix C program
  3. Product of matrix C program
  4. Sum of diagonal elements C program
  5. Sum of all corner elements C program

No comments:

Post a Comment