C Programm to Multiplying two matrices

In this c programming example we will learn how to multiply given two matrices. When we multiply two matrices the first matrix number of columns must be equal to the row of second matrix.

Before write the program first check how the multiplication of the matrices will work.

Suppose we have two matrices like below

2X3 matrix

3 9 7
1 5 4

 

3X4 matrix

6 2 8 1
3 9 4 0
5 3 1 3

 

So the multiplication will takes like first row [3 9 6] with first column of 2 matrix

6
3
5

Hence, the element in first row, first column in the resultant matrix will be as follows:

(3×6)+(9×3)+(7×5)

=18 + 27 + 35

=80

similarly remaining rows and columns will multiply and final out put will be like this

80 108 67 24
41 59 32 13

 

Let's write the program

 

#include <stdio.h>
int main()
{
 int matA[2][3], matB[3][4], matR[2][4];
 int i,j,k;
 printf("Enter elements of the first matrix of order 2 x 3 \n");
 for(i=0;i<2;i++)
 {
 for(j=0;j<3;j++)
 {
 scanf("%d",&matA[i][j]);
 }
 }
 printf("Enter elements of the second matrix of order 3 x 4 \n");
 for(i=0;i<3;i++)
 {
 for(j=0;j<4;j++)
 {
     scanf("%d",&matB[i][j]);
 }
 }
 for(i=0;i<2;i++)
 {
 for(j=0;j<4;j++)
 {
 matR[i][j]=0;
 for(k=0;k<3;k++)
 {
 matR[i][j]=matR[i][j]+matA[i][k]*matB[k][j];
 }
 }
 }
 printf("\nFirst Matrix is \n");
 for(i=0;i<2;i++)
 {
 for(j=0;j<3;j++)
 {
 printf("%d\t",matA[i][j]);
 }
 printf("\n");
 }
 printf("\nSecond Matrix is \n");
 for(i=0;i<3;i++)
 {
 for(j=0;j<4;j++)
 {
 printf("%d\t",matB[i][j]);
 }
 printf("\n");
 }
 printf("\nMatrix multiplication is \n");
 for(i=0;i<2;i++)
 {
 for(j=0;j<4;j++)
 {
 printf("%d\t",matR[i][j]);
 }
 printf("\n");
 }
 return 0;
}

 

Output:

Enter elements of the first matrix of order 2 x 3
3
9
7
1
5
4
Enter elements of the second matrix of order 3 x 4
6
2
8
1
3
9
4
0
5
3
1
3

First Matrix is
3       9       7
1       5       4

Second Matrix is
6       2       8       1
3       9       4       0
5       3       1       3

Matrix multiplication is
80      108     67      24
41      59      32      13

 

Subscribe For Daily Updates