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 2 // Also ROW2 #define COL2 2 int main() { // Step 1: Declare and initialize matrices int matrixA[ROW1][COL1] = { {1, 2}, {3, 4} }; int matrixB[COL1][COL2] = { // COL1 of matrixA must be ROW of matrixB {5, 6}, {7, 8} }; int matrixC[ROW1][COL2]; // Resultant matrix // Step 2: Check for compatibility (COL1 of A must equal ROW1 of B, which is COL1 here) // In this example, COL1 (2) matches ROW of matrixB (which is COL1 itself). // This check is often more explicit when dimensions are user-defined. // For fixed sizes as defined by #define, we ensure compatibility by design. // Step 3: Perform matrix multiplication // Outer loop iterates through rows of matrixA (and resultant matrixC) for (int i = 0; i < ROW1; i++) { // Middle loop iterates through columns of matrixB (and resultant matrixC) for (int j = 0; j < COL2; j++) { matrixC[i][j] = 0; // Initialize element of resultant matrix to 0 // Inner loop iterates through columns of matrixA (and rows of matrixB) for (int k = 0; k < COL1; k++) { // Or ROW2, they are the same matrixC[i][j] += matrixA[i][k] * matrixB[k][j]; } } } // Step 4: Print the resultant matrix printf("Resultant Matrix C (%dx%d):\n", ROW1, COL2); for (int i = 0; i < ROW1; i++) { for (int j = 0; j < COL2; j++) { printf("%d\t", matrixC[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS