C Matrix Multiplication Program
To multiply matrix A (r1 x c1) with matrix B (c1 x c2), the number of columns of A must be equal to the number of rows of B. The result has r1 rows and c2 columns. Each element is the sum of the products of a row of A and a column of B.
#include <stdio.h>
int main(void) {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int result[2][2] = {{0, 0}, {0, 0}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%4d", result[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Output of the above program is
58 64
139 154
How it works
- The first element is
1*7 + 2*9 + 3*11 = 58. - The loop
igoes through the rows of A,jthrough the columns of B, andkadds the products. - The result matrix must start with zeros, because we use
+=.
Note:
The time taken is proportional to r1 x c2 x c1, so it grows fast for big matrices. Related: Two Dimensional Arrays and Nested Loops.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |