0

C Program to subtract two matrices.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[5][5],b[5][5],m,n,sum;
clrscr();
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++)
  {
   sum=b[i][j] – a[i][j];
   printf(”  %d”,sum);
   sum=0;
  }
  printf(“\n”);
}
getch();
}

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

4 5 6          2 3 3       2 2 3
4 5 5 - 2 3 3 = 2 2 2
3 7 8 1 2 4 2 5 4

If you noticed carefully then you must had found the way matrix subtracts. The procedure of matrix subtraction is subtracting the elements of same index or in simple we can say that subtracting the element which are on same position. So this means two matrix should be have same rows and columns to perform subtraction 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 subtracting the two matrices by the statement  sum=b[i][j] – a[i][j]; here the elements at same index of the matrices are getting subtracted.

ks007

Leave a Reply

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