Matrix Multiplication in C program
Table of contents
// Matrix Multiplication
#include<stdio.h>
int main() {
int r1, c1, r2, c2, i, j, k;
printf("Enter number of rows for first matrix: ");
scanf("%d", &r1);
printf("Enter number of columns for first matrix: "); scanf("%d", &c1);
printf("Enter number of rows for second matrix: "); scanf("%d", &r2);
printf("Enter number of columns for second matrix: "); scanf("%d", &c2);
if (c1 != r2) { printf("Matrix multiplication not possible!\n"); return 1; }
printf("Enter elements of first matrix:\n");
int mat1[r1][c1], mat2[r2][c2];
for(i = 0; i < r1; i++) {
for(j = 0; j < c1; j++) {
scanf("%d", &mat1[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for(i = 0; i < r2; i++) {
for(j = 0; j < c2; j++) {
scanf("%d", &mat2[i][j]);
}
}
printf("First Matrix:\n");
for(i = 0; i < r1; i++) {
for(j = 0; j < c1; j++) {
printf("%d\t", mat1[i][j]);
}
printf("\n");
}
printf("Second Matrix:\n");
for(i = 0; i < r2; i++) {
for(j = 0; j < c2; j++) {
printf("%d\t", mat2[i][j]);
} printf("\n");
}
int res[r1][c2];
printf("Result Matrix:\n");
for(i = 0; i < r1; i++) {
for(j = 0; j < c2; j++) {
res[i][j] = 0;
for(k = 0; k < c1; k++) {
res[i][j] = res[i][j] + mat1[i][k] * mat2[k][j];
}
printf("%d\t", res[i][j]);
}
printf("\n");
}
return 0;
}
Enter number of rows for first matrix: 2
Enter number of columns for first matrix: 2
Enter number of rows for second matrix: 2
Enter number of columns for second matrix: 2
Enter elements of first matrix:
1 2
1 2
Enter elements of second matrix:
1 2
1 2
First Matrix:
1 2
1 2
Second Matrix:
1 2
1 2
Result Matrix:
3 6
3 6
Subscribe to my newsletter
Read articles from Raunak Kaushal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Raunak Kaushal
Raunak Kaushal
Hi, I'm Raunak Kaushal, a BCA student at Lucknow University's main campus, passionate about becoming a software developer. ๐ With a knack for problem-solving and a passion for teaching online, I thrive as a team leader. ๐ Currently, I'm on an exciting journey of continuous learning, aiming to shape a brighter future in tech. Let's code and innovate together!