#include #include #include void readMatrix(int **, int, int); void printMatrix(int **, int, int); int **allocMatrix(int, int); void freeMatrix(int **a, int m); int ** sumMatrix(int **a, int **b, int m, int n); int ** mulMatrix(int **a, int **b, int m, int n, int p); int main(){ int **a, **b, **c; int m, n, p; printf("enter the number m of rows of first matrix:"); scanf("%d", &m); printf("enter the number n of columns of first matrix/rows of second matrix:"); scanf("%d", &n); printf("enter the number p of columns of second matrix:"); scanf("%d", &p); a = allocMatrix(m, n); b = allocMatrix(n, p); if( a == NULL || b == NULL) { printf("not enough memory\n"); return 1; } printf("enter the first matrix:\n"); readMatrix(a,m,n); printf("enter the second matrix:\n"); readMatrix(b,n,p); c = mulMatrix(a,b,m,n,p); if( c == NULL){ printf("not enough memory\n"); return 1; } printf("The product of the matrices:\n"); printMatrix(a,m,n); printf("and\n"); printMatrix(b,n,p); printf("are\n"); printMatrix(c,m,p); } int ** sumMatrix(int **a, int ** b, int m, int n) { int **c; c = allocMatrix(m,n); if( c == NULL) return NULL; for(int i = 0; i < m; i ++){ for(int j = 0; j < n; j ++){ c[i][j] = a[i][j] + b[i][j]; } } return c; } void readMatrix(int **a, int m, int n){ for(int i = 0; i < m; i ++){ for(int j = 0; j < n; j ++){ printf("\tenter [%d][%d] th entry:",i,j); scanf("%d",&a[i][j]); } } } void printMatrix(int **a, int m, int n){ for(int i = 0; i < m; i ++){ printf("\t"); for(int j = 0; j < n; j++){ printf("%d\t",a[i][j]); } printf("\n"); } } int **allocMatrix(int m, int n) { int **a; a = (int **) malloc(m * sizeof(int *)); if( a == NULL) return NULL; for(int i = 0 ; i < m; i ++){ a[i] = (int *) malloc(n * sizeof(int)); if(a[i] == NULL){ for(int j = 0; j < i; j ++){ free(a[j]); a[j]=NULL; } return NULL; } } return a; } int **mulMatrix(int **a, int **b, int m, int n, int p) { int **c; c = allocMatrix(m,p); if ( c == NULL ) return NULL; for(int i = 0; i < m; i ++){ for(int k=0; k < p; k++){ c[i][k] = 0; for(int j = 0; j < n; j ++){ c[i][k] = c[i][k] + a[i][j] * b[j][k]; } } } return c; }