In this section, we are writing a program for multiplication of two matrices of order mXn.

For example, if the order of two matrices are 2X2.

Then, to do the multiplication we require two input matrices and to store the result one result matrix is required.

For example:

First matrix:

1 3

4 1

Second matrix:

4 1

3 1

result matrix:

13 4

19 5

To write this program, do the following things.

Step 1: read the order of the first matrix

Step 2: read the first matrix elements

Step 3: read the order of the second matrix

Step 4: if the columns of the first matrix and rows of the second matrix is not equal, matrix multiplication is not possible. write this condition.

Step 4: write the logic for multiplication and store it in result matrix.

Step 5: print the result matrix.

#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
// reading the order of the first matrix
printf("Enter the number of rows and Columns");
scanf("%d %d", &m, &n);
// reading the first matrix
printf("Enter the elements of first matrix\n");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);
// reading the order of the second matrix
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
// check the first matrix columns is equal to second matrix rows
if ( n != p )
printf("Matrix multiplication is not possible\n");
else
{
printf("Enter the elements of second matrix\n");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
scanf("%d", &second[c][d]);
// matrix multiplication logic.
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
// print the resultant matrix
printf("The resultant matrix is: \n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}

Matrix Multiplication

Output:

Command Prompt

Enter the number of rows and Columns
3
3
Enter the elements of first matrix
1 2 3
3 2 1
4 3 2
Enter the number of rows and columns of second matrix
3
3
Enter the elements of second matrix
4 1 3
5 6 7
1 4 3
Product of entered matrices:-
17 25 26
23 19 26
33 30