118k views
5 votes
6. Write a program that can multiply an n x m matrix and m x n matrix together: The input specifications are these: Read n and m using scanf function. Read two matrices using a for loop inside the main function. The output (product) matrix must be computed in a function named matrix_mult which will have the two input matrices as arguments.

User Shawnwall
by
3.3k points

1 Answer

6 votes

Answer:

see explaination

Step-by-step explanation:

#include <stdio.h>

#include <malloc.h>

void matrix_mult(int **m1, int **m2, int **m3, int n, int m) {

int i, j, k, sum=0;

for(i = 0; i < n; ++i) {

for(j = 0; j < n; ++j) {

sum = 0;

for(k = 0; k < m; ++k) {

sum += m1[i][k] * m2[k][j];

}

m3[i][j] = sum;

}

}

}

int main() {

int n, m, i, j;

int **m1, **m2, **m3;

printf("Enter number of rows: ");

scanf("%d", &n);

printf("Enter number of columns: ");

scanf("%d", &m);

m1 = malloc(sizeof(int *) * n);

m2 = malloc(sizeof(int *) * m);

m3 = malloc(sizeof(int *) * n);

for(i = 0; i < m; ++i) {

m1[i] = malloc(sizeof(int) * m);

m2[i] = malloc(sizeof(int) * n);

m3[i] = malloc(sizeof(int) * n);

}

printf("Enter first matrix\\");

for(i = 0; i < n; ++i) {

for(j = 0; j < m; ++j) {

scanf("%d", &(m1[i][j]));

}

}

printf("Enter second matrix\\");

for(i = 0; i < m; ++i) {

for(j = 0; j < n; ++j) {

scanf("%d", &(m2[i][j]));

}

}

matrix_mult(m1, m2, m3, n, m);

printf("product is\\");

for(i = 0; i < n; ++i) {

for(j = 0; j < n; ++j) {

printf("%d ", m3[i][j]);

}

printf("\\");

}

printf("Enter first matrix: ");

return 0;

}

User Mudassir Ali
by
4.0k points