C program to calculate subtraction of two matrix

C program to calculate subtraction of two matrix:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().



#include<stdio.h>
#include<stdlib.h>

main()
{
   int i,j,m1[10][10],m2[10][10],m3[10][10];
   int row1,col1,row2,col2;

   printf("Enter the number of Rows for Matrix 1 : ");
   scanf("%d",&row1);
   printf("\nEnter the number of Columns for Matrix 1 : ");
   scanf("%d",&col1);

   printf("\nEnter the number of Rows for Matrix 2 : ");
   scanf("%d",&row2);
   printf("\nEnter the number of Columns for Matrix 2 : ");
   scanf("%d",&col2);

   //Check if no of rows and columns of both matrices are equal
   if (row1 != row2 || col1 != col2)
    {
      printf("\nRows and Columns of matrices is not same ");
      exit(0);
    }

   //Accepting the Elements in Matrix 1
   printf("Enter the first %d*%d Matrix: \n",row1,col1);
   for(i=0;i<row1;i++)
    {
      for(j=0;j<col1;j++)
      {
         scanf("%d",&m1[i][j]);
      }
   }

   //Accepting the Elements in Matrix 2
   printf("Enter the second %d*%d Matrix: \n",row2,col2);
   for(i=0;i<row2;i++)
    {
      for(j=0;j<col2;j++)
       {
         scanf("%d",&m2[i][j]);
       }
    }

   //Subtraction of two matrices
   for(i=0;i<row1;i++)
   {
      for(j=0;j<col1;j++)
       {
         m3[i][j]=m1[i][j]-m2[i][j];
       }
   }

   //Printing the matrix
   printf("\nThe Subtraction of two Matrices is :\n");
   for(i=0;i<row1;i++)
    {
      for(j=0;j<col1;j++)
      {
         printf("%d\t",m3[i][j]);
      }
      printf("\n");
   }
}

OUTPUT:

Enter the number of Rows for Matrix 1 : 3

Enter the number of Columns for Matrix 1 : 3

Enter the number of Rows for Matrix 2 : 3

Enter the number of Columns for Matrix 2 : 3
Enter the first 3*3 Matrix:
1 4 7
5 3 1
7 8 4
Enter the second 3*3 Matrix:
4 9 5
7 8 3
1 7 6

The Subtraction of two Matrices is :
-3      -5      2
-2      -5      -2
6       1       -2

 

Leave a Reply

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

15 + 1 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.