C program for multiplication 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().

/**Multiplication of matrices**/
#include<stdio.h>
 main()
{
 int a[100][100],b[100][100],c[100][100],i,j,m,n,p,q,k;
 int sum=0;

 printf("Enter how many rows and columns of first matrix\n");
 scanf("%d%d",&m,&n);//m=row, n=column

 //first matrix input
 printf("Enter first matrix\n");
 for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
  {
   scanf("%d",&a[i][j]);
  }
 }
 printf("Enter how many rows and columns of second matrix\n");
 scanf("%d%d",&p,&q);//m=row, n=column
 if(n!=p)
 {
  printf("Multiplication of these matrices cant be done\n");
 }
 else
 {
   //second matrix input
   printf("Enter Second matrix\n");
   for(i=0;i<p;i++)
   {
    for(j=0;j<q;j++)
    {
     scanf("%d",&b[i][j]);
    }
   }

  //multiplication of matrix
 for(i=0;i<m;i++)
 {
  for(j=0;j<q;j++)
  {
   for(k=0;k<p;k++)
   {
    sum=sum+a[i][k]*b[k][j];
   }
    c[i][j]=sum;

  }
 }

 //Printinf first matrix
 printf("First matrix is\n");
 for(i=0;i<m;i++)
 {
  printf("\n");
  for(j=0;j<n;j++)
  {
   printf("%d\t",a[i][j]);
  }
 }

 //Printing second matrix
 printf("\nSecond matrix is\n");
 for(i=0;i<m;i++)
 {
  printf("\n");
  for(j=0;j<n;j++)
  {
    printf("%d\t",b[i][j]);
  }
 }

 //Printing the addition of an matrix
 printf("\nMultiplication of two matrix is\n");
 for(i=0;i<m;i++)
 {
  printf("\n");
  for(j=0;j<n;j++)
  {
   printf("%d\t",c[i][j]);
  }
 }
}//else closed
}//main closed

OUTPUT:

Enter how many rows and columns of first matrix
3 3
Enter first matrix
1 2 4
1 3 5
2 7 4
Enter how many rows and columns of second matrix
3 3
Enter Second matrix
1 2 4
1 6 4
3 5 7
First matrix is

1       2       4
1       3       5
2       7       4
Second matrix is

1       2       4
1       6       4
3       5       7
Multiplication of two matrix is

15      49      89
108     153     204
225     291     355

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.