C program for addition of two matrices

C program for addition of two matrices:
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>
main()
{
   int i,j,mat1[10][10],mat2[10][10],mat3[10][10];
   int row1,col1,row2,col2;

   printf("Enter the number of Rows of Matrix1 : ");
   scanf("%d", &row1);
   printf("\nEnter the number of Cols of Matrix1 : ");
   scanf("%d", &col1);

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

   /* Before accepting the Elements Check if no of
    rows and columns are same or not*/
   if (row1 != row2 || col1 != col2)
    {
      printf("\nOrder of two matrices is not same ");
    }
    else
    {
      //Accept the Elements in first Matrix 
      printf("Enter First Matrix\n");
      for(i=0;i<row1;i++)
       {
         for(j=0;j<col1;j++)
         {
            scanf("%d",&mat1[i][j]);
         }
       }

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

      //Addition of matrices
      for(i=0;i<row1;i++)
         {
         for(j=0;j<col1;j++)
            {
            mat3[i][j]=mat1[i][j] + mat2[i][j];
            }
         }

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

OUTPUT:

Enter the number of Rows of Matrix1 : 3

Enter the number of Cols of Matrix1 : 3

Enter the number of Rows of Matrix2 : 3

Enter the number of Columns of Matrix2 : 3
Enter First Matrix
1 2 3
4 2 1
5 2 3
Enter Second Matrix
4 5 6
1 5 4
2 5 7

The Addition of two Matrices is :
5       7       9
5       7       5
7       7       10

-----------------------------------------------------------------------

Enter the number of Rows of Matrix1 : 3

Enter the number of Cols of Matrix1 : 4

Enter the number of Rows of Matrix2 : 3

Enter the number of Columns of Matrix2 : 5

Order of two matrices is not same

 

Leave a Reply

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

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