C Program to multiply two matrix.
Objective
Write a C program to multiply two matrices.
Algorithm / Approach
- Declare
m1as 3x2,m2as 2x4, and the resultm3as 3x4. - Read the data for
m1andm2. - Use THREE nested loops (
ifor M1 rows,jfor M2 cols,kfor the common inner dimension). - Calculate the dot product for each cell:
sum = sum + m1[i][k] * m2[k][j]. - Assign the sum to
m3[i][j]and resetsum = 0. - Print the final product matrix.
main.c
#include<stdio.h>
int main( ) {
int r1=3, c1=2, r2=2, c2=4;
int i, j, k, sum = 0;
int m1[3][2], m2[2][4], m3[3][4];
printf("Enter elements of mat1: ");
for (i = 0; i < r1; i++){
for (j = 0; j < c1; j++){
scanf("%d", &m1[i][j]);
}
}
printf("Enter elements mat2: ");
for (i = 0; i < r2; i++){
for (j = 0; j < c2; j++){
scanf("%d", &m2[i][j]);
}
}
for (i=0; i < r1; i++){
for (j=0; j < c2; j++){
for (k=0; k < r2; k++){
sum = sum + m1[i][k]*m2[k][j];
}
m3[i][j] = sum;
sum = 0;
}
}
printf("Product of Matrix : \n");
for (i=0; i < r1; i++) {
for (j=0; j < c2; j++){
printf("%d ", m3[i][j]);
}
printf("\n");
}
return 0;
}
Expected Output
Enter elements of mat1 : 1 3 3 4 2 3 Enter elements of mat2 : 1 2 3 4 3 4 5 6 Product of Matrix : 10 14 18 22 15 22 29 36 11 16 21 26
Explanation of the Program
- Matrix multiplication is much more complex than addition. You must calculate the "dot product" of the rows of the first matrix against the columns of the second matrix.
- Rule of Matrix Multiplication: The number of columns in the first matrix MUST equal the number of rows in the second matrix. (e.g., a 3x2 matrix can multiply a 2x4 matrix, resulting in a 3x4 matrix).
- This requires three nested loops: two to traverse the resulting matrix grid, and a third (
k) to calculate the sliding dot product.
Complexity
Time Complexity
O(r1 * c2 * r2) - Cubic time complexity.
Space Complexity
O(r1 * c2) - To store the resulting matrix.