#include #define SIZE 4 int read_matrix(); void multiply_matrix(); void output_matrix(); int main() { int A[SIZE][SIZE]; int A_rows, A_cols; // size of A int B[SIZE][SIZE]; int B_rows, B_cols; // size of B int C[SIZE][SIZE]; int C_rows, C_cols; // size of C int err; err = read_matrix("Input first matrix:\n", A, &A_rows, &A_cols); if (err < 0) return 0; err = read_matrix("Input second matrix:\n", B, &B_rows, &B_cols); if (err < 0) return 0; if (A_cols != B_rows) { // cannot multiply matrices printf("Matrix sizes do not match!\n"); return 0; } multiply_matrix(A, A_rows, A_cols, B, B_cols, C); output_matrix("The product matrix is:\n", C, A_rows, B_cols); } /* Reads a vector */ void read_vector(int vector[], int size) { for (int i = 0; i < size; i++) scanf("%d", &vector[i]); } /* Reads matrix A from input */ int read_matrix(char *statement, int A[][SIZE], int *rows, int *cols) { printf(statement); printf("Enter number of rows: "); scanf("%d", rows); printf("Enter number of columns: "); scanf("%d", cols); if ((*rows > SIZE) || (*cols > SIZE)) { // error, exit printf("Matrix too large!\n"); return -1; } printf("Enter the matrix now:\n"); for (int i = 0; i < *rows; i++) // read i-th row read_vector(A[i], *cols); return 0; // all OK } /* Calculates C = A * B */ void multiply_matrix(int A[][SIZE], int A_rows, int A_cols, int B[][SIZE], int B_cols, int C[][SIZE]) { for (int i = 0; i < A_rows; i++) for (int j = 0; j < B_cols; j++) { C[i][j] = 0; // initialize for (int k = 0; k < A_cols; k++) C[i][j] = C[i][j] + A[i][k] * B[k][j]; } } /* Outputs matrix A */ void output_matrix(char *statement, int A[][SIZE], int rows, int cols) { printf(statement); for (int i = 0; i < rows; i++) { // output i-th row for (int j = 0; j < cols; j++) // output j-th element of i-th row printf("%d ", A[i][j]); printf("\n"); } }