C Online Compiler
Example: Matrix Multiplication in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Multiplication #include <stdio.h> #define ROW1 2 #define COL1 3 #define ROW2 3 #define COL2 2 int main() { // Step 1: Declare and initialize matrices int matrix1[ROW1][COL1] = { {1, 2, 3}, {4, 5, 6} }; int matrix2[ROW2][COL2] = { {7, 8}, {9, 1}, {2, 3} }; int resultMatrix[ROW1][COL2]; // Resultant matrix dimensions // Step 2: Check for multiplication compatibility // Number of columns in matrix1 must be equal to number of rows in matrix2 if (COL1 != ROW2) { printf("Error: Matrices cannot be multiplied. Number of columns in first matrix must equal number of rows in second matrix.\n"); return 1; // Indicate error } // Step 3: Perform matrix multiplication printf("Multiplying Matrix 1 (%dx%d) by Matrix 2 (%dx%d):\n", ROW1, COL1, ROW2, COL2); // Loop through rows of result matrix for (int i = 0; i < ROW1; i++) { // Loop through columns of result matrix for (int j = 0; j < COL2; j++) { resultMatrix[i][j] = 0; // Initialize element to 0 // Loop through elements for dot product for (int k = 0; k < COL1; k++) { // Or k < ROW2, since COL1 == ROW2 resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j]; } } } // Step 4: Display the result matrix printf("\nResultant Matrix (%dx%d):\n", ROW1, COL2); for (int i = 0; i < ROW1; i++) { for (int j = 0; j < COL2; j++) { printf("%d\t", resultMatrix[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS