Loading your workspace…
Loading your workspace…
Multiply two matrices and check the multiplication rule first: the number of columns of the first matrix must equal the number of rows of the second.
#include <stdio.h>
#define MAX 10
int main(void) {
int a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];
int r1, c1, r2, c2, i, j, k, sum;
printf("Enter rows and columns of matrix A:\n");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns of matrix B:\n");
scanf("%d %d", &r2, &c2);
if (r1 < 1 || c1 < 1 || r2 < 1 || c2 < 1 || r1 > MAX || c1 > MAX || r2 > MAX || c2 > MAX) {
printf("Error: each dimension must be between 1 and %d\n", MAX);
return 1;
}
if (c1 != r2) {
printf("Error: cannot multiply a %dx%d matrix by a %dx%d matrix (%d columns vs %d rows)\n",
r1, c1, r2, c2, c1, r2);
return 1;
}
printf("Enter matrix A:\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter matrix B:\n");
for (i = 0; i < r2; i++) {
for (j = 0; j < c2; j++) {
scanf("%d", &b[i][j]);
}
}
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
sum = 0;
for (k = 0; k < c1; k++) {
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
printf("Product matrix:\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}
Input
2 3
3 2
1 2 3
4 5 6
7 8
9 10
11 12Output
Enter rows and columns of matrix A:
Enter rows and columns of matrix B:
Enter matrix A:
Enter matrix B:
Product matrix:
58 64
139 154Input
2 3
2 2Output
Enter rows and columns of matrix A:
Enter rows and columns of matrix B:
Error: cannot multiply a 2x3 matrix by a 2x2 matrix (3 columns vs 2 rows)The rule is checked before any element is read, because the result would otherwise be undefined. A matrix with r1 rows and c1 columns times one with r2 rows and c2 columns is defined only when c1 = r2, and the result then has r1 rows and c2 columns.
Each result cell is the dot product of a row of A with a column of B. The three nested loops follow that definition directly: i and j pick the cell and k walks along the shared dimension.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
2 3 3 2 1 2 3 4 5 6 7 8 9 10 11 12
Expected output
Enter rows and columns of matrix A: Enter rows and columns of matrix B: Enter matrix A: Enter matrix B: Product matrix: 58 64 139 154
2 3 2 2
Expected output
Enter rows and columns of matrix A: Enter rows and columns of matrix B: Error: cannot multiply a 2x3 matrix by a 2x2 matrix (3 columns vs 2 rows)
The product exists only when n = p, and then it is m x q.
No. In general AB and BA are different, and one of them may not even be defined.
k. It sums over the columns of A and the rows of B.
Each result cell is a new dot product; a stale sum would carry values from the previous cell.
O(r1 * c1 * c2), from the three nested loops.
Back to all VTU BPOPS103 lab programs.