Let A[nl][ml] and B[n2][m2] be an n x m matrix. Then, find product of C[n] [m], is a A and B is defined as C(i,k) = A(ij) x B(j,k). where j is multipied over for all possible values of i and k.
Input:
2 3
3 2
3 -2 5
3 0 4
2 3
-9 0
0 4
Output:
24 29
6 25
#include <stdio.h>
#include <stdlib.h>
#define N 100
void ReadMatrix(int M[N][N], int n, int m)
{
int i, j;
for (i=0; i<n; i++) {
for (j=0; j<m; j++) {
scanf("%d", &M[i][j]);
}
}
}
void PrintMatrix(int M[N][N], int n, int m)
{
int i, j;
for (i=0; i<n; i++) {
for (j=0; j<m; j++) {
printf("%3d ", M[i][j]);
}
printf("\n");
}
}
void MultMatrix(int A[N][N], int n1, int m1,
int B[N][N], int n2, int m2,
int C[N][N])
{
int i, j, k;
if (m1 != n2) {
printf("Incorect matixes size");
exit(1);
}
for (i=0; i<n1; i++) {
for (j=0; j<m2; j++) {
C[i][j] = 0;
for (k=0; k<m1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
int main()
{
int A[N][N], B[N][N], C[N][N];
int n1, m1, n2, m2;
scanf("%d %d", &n1, &m1);
scanf("%d %d", &n2, &m2);
ReadMatrix(A, n1, m1);
ReadMatrix(B, n2, m2);
MultMatrix(A, n1, m1, B, n2, m2, C);
printf("\n");
PrintMatrix(C, n1, m2);
return 0;
}
Comments
Leave a comment