Multiplication of Two Matrix in C of Same Dimensions using For loop
ADVERTISEMENTS
Multiplication of two matrix in C of same dimensions using for loop. In this article, you will learn how to make program of multiplication of two matrix in c of same dimensions using for loop.
Matrix Multiplication Formula
{ M1 } x { M2 } = { M3 }
Source Code
// Multiplication of Two Matrix in C of Same Dimensions using For loop
#include <stdio.h>
int main() {
int r, c, i, j, k;
// r - To store the number of rows
// c - To store the number of columns
printf("---Enter the number of rows of the first matrix---\n");
scanf("%d", &r);
printf("---Enter the number of columns of the first matrix----\n");
scanf("%d", &c);
int x[r][c], y[r][c], m[r][c];
// x - To store the first matrix elements
// y - To store the second matrix elements
// m - To store the multiplication of matrices
printf("---Enter the first matrix's elements---\n");
for (i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
scanf("%d", &x[i][j]);
}
}
printf("---Enter the second matrix's elements---\n");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
scanf("%d", &y[i][j]);
}
}
printf("\n\n-----The multiplication of the matrices is-----\n\n");
// It's the calculation of matrices's multiplications
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
m[i][j] = 0;
for(k = 0; k < c; k++) {
m[i][j] += x[i][k] * y[k][j];
}
}
}
// This will display matrices's outputs
for(i = 0; i < r; i++) {
printf("\t");
for(j = 0; j < c; j++) {
printf("%d\t", m[i][j]);
}
printf("\n\n");
}
return 0;
}
Output
---Enter the number of rows of the first matrix---
3
---Enter the number of columns of the first matrix----
3
---Enter the first matrix's elements---
3 5 3
5 2 1
8 0 8
---Enter the second matrix's elements---
4 5 3
6 8 3
2 5 7
-----The multiplication of the matrices is-----
48 70 45
34 46 28
48 80 80