Matrix Multiplication
Completed
Read A (n×m) and B (m×p) and print A×B.
Input
n m, A's rows, m p, B's rows.
Output
n rows.
Example
Input
2 2 1 2 3 4 2 2 5 6 7 8
Output
19 22 43 50
Editor
C
Hints
Cell (i, j) is the sum of a[i][k] * b[k][j] over k.
Solution explanation
Three nested loops: rows of A, columns of B, and the shared dimension.
Show solution
#include <stdio.h>
int main() {
int n, m, p, a[10][10], b[10][10];
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf("%d", &a[i][j]);
scanf("%d %d", &m, &p);
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++)
scanf("%d", &b[i][j]);
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
int s = 0;
for (int k = 0; k < m; k++) s += a[i][k] * b[k][j];
printf("%d%s", s, j < p - 1 ? " " : "\n");
}
}
return 0;
}