C Online Compiler
Example: Matrix Multiplication Fixed Size in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Multiplication Fixed Size #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 result[ROW1][COL2]; // Result matrix dimensions: ROW1 x COL2 // Step 2: Check for valid multiplication dimensions // For multiplication, COL1 must be equal to ROW2 if (COL1 != ROW2) { printf("Error: Matrices cannot be multiplied. Number of columns in Matrix1 must equal number of rows in Matrix2.\n"); return 1; // Indicate an error } // Step 3: Initialize the result matrix with zeros for (int i = 0; i < ROW1; i++) { for (int j = 0; j < COL2; j++) { result[i][j] = 0; } } // Step 4: Perform matrix multiplication // Outer loops iterate through rows of matrix1 (i) and columns of matrix2 (j) for (int i = 0; i < ROW1; i++) { for (int j = 0; j < COL2; j++) { // Inner loop calculates the dot product for (int k = 0; k < COL1; k++) { // Or k < ROW2, since COL1 == ROW2 result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } // Step 5: Print the result 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", result[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS