0

C program to add two matrices.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[5][5],b[5][5],m,n,sub;
clrscr();
printf(“Enter the number of rows and columns for matrices:(max 5)”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of first matrix”);
for(i=0;i<m;i++)
{
 for(j=0;j<n;j++)
  {
   scanf(“%d”,&a[i][j]);
  }
}
printf(“Enter the elements of second matrix”);
for(i=0;i<m;i++)
{
 for(j=0;j<n;j++)
  {
   scanf(“%d”,&b[i][j]);
  }
}
printf(“\nOn subtraction we get…. \n”);
for(i=0;i<m;i++)
{ printf(“\n”);
 for(j=0;j<n;j++)
  {
   sub=b[i][j]-a[i][j];
   printf(”  %d”,sub);
   sub=0;
  }
  printf(“\n”);
}
getch();
}

Before explaining code let’s see how the matrix get Add. for example we have two matrices.

4 5 6          2 3 3       6 8 9
4 5 5 + 2 3 3 = 6 8 8
3 7 8 1 2 4 4 9 12

If you noticed carefully then you must had found the way matrix Adds. The procedure of matrix addition is adding the elements of same index or in simple we can say that adding the element which are on same position. So this means two matrix should be have same rows and columns to perform addition operation.

Now lets look at the code:

Here we have pre defined size of matrices but you can add a condition where you check if both matrix have same size.

Then we have for loops for entering the two matrix. now the main logic starts in the next for loop where we are adding the two matrices by the statement  sum=b[i][j] + a[i][j]; here the elements at same index of the matrices are getting added.



ks007

Leave a Reply

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