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 // Rows of first matrix #define COL1 3 // Columns of first matrix #define ROW2 3 // Rows of second matrix #define COL2 2 // Columns of second matrix int main() { // Step 1: Declare matrices and result matrix int matrixA[ROW1][COL1] = { {1, 2, 3}, {4, 5, 6} }; int matrixB[ROW2][COL2] = { {7, 8}, {9, 10}, {11, 12} }; int resultMatrix[ROW1][COL2]; // Resulting matrix dimensions: ROW1 x COL2 // Check if multiplication is possible if (COL1 != ROW2) { printf("Error: Matrix multiplication not possible. Number of columns in Matrix A must be equal to number of rows in Matrix B.\n"); return 1; // Indicate an error } // Step 2: Initialize result matrix elements to 0 for (int i = 0; i < ROW1; i++) { for (int j = 0; j < COL2; j++) { resultMatrix[i][j] = 0; } } // Step 3: Perform matrix multiplication // i iterates through rows of matrixA (and resultMatrix) for (int i = 0; i < ROW1; i++) { // j iterates through columns of matrixB (and resultMatrix) for (int j = 0; j < COL2; j++) { // k iterates through columns of matrixA (and rows of matrixB) for (int k = 0; k < COL1; k++) { // Or ROW2, they must be equal resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j]; } } } // Step 4: Display the result matrix printf("Resultant Matrix C (A * B):\n"); 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