In this section, we will write a C Program to Multiply Two Matrices using multi-dimensional array. You may go through the c topics below, before starting.
Matrix multiplication in C: We can add, subtract, multiply or divide two matrices in C. The program takes inputs for the numbers of rows and columns and elements themselves. And then we perform the multiplication operation using for loop in C.
The matrix multiplication is done by multiplying the first matrix one-row element with the second matrix all column elements.
NOTE: Condition for multiplication of matrix:- the number of columns of the first matrix should be equal to the number of rows of the second matrix.
C Program for Matrix Multiplication
We will take the rows and columns values once from the user for both the matrices.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <stdio.h> int main() { int a[10][10], b[10][10], mul[10][10], r, c, i, j, k; printf("Enter the number of ROWS: "); scanf("%d", &r); printf("Enter the number of COLUMNS: "); scanf("%d", &c); printf("\nEnter the element for the FIRST matrix: \n"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { printf("a[%d][%d] = ", i, j); scanf("%d", &a[i][j]); } } printf("\nEnter the element for the SECOND matrix: \n"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { printf("b[%d][%d] = ", i, j); scanf("%d", &b[i][j]); } } printf("\nMatrix Multiplication: \n"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { mul[i][j] = 0; for (k = 0; k < c; k++) { mul[i][j] += a[i][k] *b[k][j]; } } } //print the result for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { printf("%d\t", mul[i][j]); } printf("\n"); } return 0; } |
Output:
Enter the number of ROWS: 2
Enter the number of COLUMNS: 2
Enter the element for the FIRST matrix:
a[0][0] = 2
a[0][1] = 2
a[1][0] = 2
a[1][1] = 2
Enter the element for the SECOND matrix:
b[0][0] = 3
b[0][1] = 3
b[1][0] = 3
b[1][1] = 3
Matrix Multiplication:
12 12
12 12