Array Exercises
Write a C program to read elements in two matrices and multiply them. Matrix multiplication program in C. How to multiply matrices in C. Logic to multiply two matrices in C programming.
Required knowledge
Basic C programming, C for loop, ArrayS
Matrix Multiplication
Two matrices can be multiplied only and only if number of columns in the first matrix is same as number of rows in second matrix. Multiplication of two matrices is defined as -

Program to multiply two matrices
/** * C program to multiply two matrices */ #include <stdio.h> #define SIZE 3 // Size of the matrix int main() { int A[SIZE][SIZE]; // Matrix 1 int B[SIZE][SIZE]; // Matrix 2 int C[SIZE][SIZE]; // Resultant matrix int row, col, i, sum; /* Input elements in first matrix from user */ printf("Enter elements in matrix A of size %dx%d: \n", SIZE, SIZE); for(row=0; row<SIZE; row++) { for(col=0; col<SIZE; col++) { scanf("%d", &A[row][col]); } } /* Input elements in second matrix from user */ printf("\nEnter elements in matrix B of size %dx%d: \n", SIZE, SIZE); for(row=0; row<SIZE; row++) { for(col=0; col<SIZE; col++) { scanf("%d", &B[row][col]); } } /* * Multiply both matrices A*B */ for(row=0; row<SIZE; row++) { for(col=0; col<SIZE; col++) { sum = 0; /* * Multiply row of first matrix to column of second matrix * and store sum of product of elements in sum. */ for(i=0; i<SIZE; i++) { sum += A[row][i] * B[i][col]; } C[row][col] = sum; } } /* Print product of the matrices */ printf("\nProduct of matrix A * B = \n"); for(row=0; row<SIZE; row++) { for(col=0; col<SIZE; col++) { printf("%d ", C[row][col]); } printf("\n"); } return 0; }
Output:
Enter elements in matrix A of size 3x3:
1 2 3
4 5 6
7 8 9
Enter elements in matrix B of size 3x3:
1 2 3
4 5 6
7 8 9
Product of matrix A * B =
30 36 42
66 81 96
102 126 150
Process returned 0 (0x0) execution time : 30.573 s
Matrix multiplication in c language
#include <stdio.h> int main() { int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], multiply[10][10]; printf("Enter the number of rows and columns of first matrix\n"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrix\n"); for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &first[c][d]); printf("Enter the number of rows and columns of second matrix\n"); scanf("%d%d", &p, &q); if (n != p) { printf("Matrices with entered orders can't be multiplied with each other.\n"); } else { printf("Enter the elements of second matrix\n"); for (c = 0; c < p; c++) for (d = 0; d < q; d++) scanf("%d", &second[c][d]); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { for (k = 0; k < p; k++) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } } printf("Product of entered matrices:-\n"); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) printf("%d\t", multiply[c][d]); printf("\n"); } } return 0; }