C Program to multiply two matrices
Last updated on September 23, 2020
The following is a C program to multiply two matrices:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | /******************************************
Program to multiply two matrices
******************************************/
#include<stdio.h> // include stdio.h
#define ROW1 2
#define COL1 2
#define ROW2 COL1
#define COL2 3
int main()
{
int i, j, arr1[ROW1][COL1],
arr2[ROW2][COL2],
arr3[ROW1][COL2];
printf("Enter first matrix (%d x %d): \n", ROW1, COL1);
// input first matrix
for(i = 0; i < ROW1; i++)
{
for(j = 0; j < COL1; j++)
{
scanf("%d", &arr1[i][j]);
}
}
printf("\nEnter second matrix (%d x %d): \n", ROW2, COL2);
// input second matrix
for(i = 0; i < ROW2; i++)
{
for(j = 0; j < COL2; j++)
{
scanf("%d", &arr2[i][j]);
}
}
printf("\narr1 * arr2 = ");
// multiply two matrices
for(i = 0; i < ROW1; i++)
{
for(j = 0; j < COL2; j++)
{
arr3[i][j] = 0;
for(int k = 0; k < COL1; k++)
{
arr3[i][j] += arr1[i][k] * arr2[k][j];
}
}
printf("\n");
}
// print the result
for(i = 0; i < ROW2; i++)
{
for(j = 0; j < COL2; j++)
{
printf("%d ", arr3[i][j]);
}
printf("\n");
}
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 3 4 5 6 7 8 9 10 11 12 | Enter first matrix (2 x 2):
2 3
4 5
Enter second matrix (2 x 3):
6 4 2
7 8 9
arr1 * arr2 =
33 32 31
59 56 53
|
How it works #
Two matrices can be multiplied only if the number of columns in the first matrix is equal to the number of rows in the second matrix.
Let, A
be the matrix of size 2x3
and B
be the matrix of size 3x2
, Then, A * B
is given by:
\[
\left(\begin{array}{ccc}a & b & c \\d & e & f\end{array}\right) * \left(\begin{array}{cc}g & h\\k &l \\o & p \end{array}\right) = \left(\begin{array}{cc}a*g + b * k + c * o &a*h + b * l + c * p \\d*g + e * k + f * o &d*h + e * l + f * p\end{array}\right)
\]
In general, If matrix A
is of size m x n
and B
is of size n x p
, then the size of matrix A * B
will be m x p
.
Here is how the program works:
- The first for loop (lines 20-26) asks the user to input the first matrix.
- The second for loop (lines 31-37) asks the user to input the second matrix.
- The third for loop (lines 42-55) multiplies the matrices.
- The fourth for loop (lines 58-65) prints the result of matrix multiplication.
Recommended Reading:
- C Program to find the maximum and minimum element in the array
- C Program to reverse the elements of an array
- C Program to sum the elements of an array
- C Program to find the count of even and odd elements in the array
- C Program to add two add Matrices
Load Comments