C Online Compiler
Example: C program to Multiply two Matrices using Multi-dimensional Arrays
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// C program to Multiply two Matrices using Multi-dimensional Arrays #include <stdio.h> // It's the main function of the program int main() { int rows_1, col_1; printf("Enter No. of Row & Column:\n"); scanf("%d %d", &rows_1, &col_1); // Transpose the dimension of the first matrix into the second matrix // M1[2 x 3] can multiply with M2[3 x 2] int rows_2 = col_1, col_2 = rows_1; int matrix_1[rows_1][col_1]; int matrix_2[rows_2][col_2]; int matrix_mul[rows_1][rows_1]; // Step-1 Enter the values of first matrix printf("\nEnter the values of the first matrix - [%d x %d]\n", rows_1, col_1); for (int i = 0; i < rows_1; i++) { for (int j = 0; j < col_1; j++) { printf("Enter value - M1[%d][%d]: ", i, j); scanf("%d", &matrix_1[i][j]); } } // Step-2 Enter the values of second matrix printf("\nEnter the values of the second matrix - [%d x %d]\n", rows_2, col_2); for (int i = 0; i < rows_2; i++) { for (int j = 0; j < col_2; j++) { printf("Enter value - M2[%d][%d]: ", i, j); scanf("%d", &matrix_2[i][j]); } } // Step-3 Initialize the multiplication matrix with 0 values for (int i = 0; i < rows_1; i++) { for (int j = 0; j < rows_2; j++) { matrix_mul[i][j] = 0; } } // Step-4 Multiply the matrices M1 & M2 and store these values in another matrices `matrix_mul` for (int i = 0; i < rows_1; i++) { for (int j = 0; j < col_2; j++) { for (int k = 0; k < col_1; k++) { matrix_mul[i][j] += matrix_1[i][k] * matrix_2[k][j]; } } } // Step-5 Final output of the program to print the final matrices printf("\nMultiplication of two matrices matrix_1 & matrix_2\n"); for (int i = 0; i < rows_1; i++) { for (int j = 0; j < col_2; j++) { printf("%d\t", matrix_mul[i][j]); } printf("\n"); } return 0; }
3 3 2 3 4 3 5 6 4 5 3 1 2 1 -1 2 1 3 2 1
Output
Clear
ADVERTISEMENTS