C Online Compiler
Example: Matrix Multiplication in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Multiplication #include <stdio.h> int main() { int r1, c1, r2, c2; // Step 1: Get dimensions for the first matrix printf("Enter rows and columns for first matrix (e.g., 2 3): "); scanf("%d %d", &r1, &c1); // Step 2: Get dimensions for the second matrix printf("Enter rows and columns for second matrix (e.g., 3 2): "); scanf("%d %d", &r2, &c2); // Step 3: Check if multiplication is possible if (c1 != r2) { printf("Error: Number of columns of first matrix must be equal to number of rows of second matrix.\n"); return 1; // Indicate an error } // Declare matrices with max size or dynamic allocation (for simplicity, using fixed large size here) // For production, consider dynamic allocation based on r1, c1, r2, c2 int matrix1[10][10], matrix2[10][10], resultMatrix[10][10]; int i, j, k; // Step 4: Input elements for the first matrix printf("\nEnter elements of first matrix:\n"); for (i = 0; i < r1; ++i) { for (j = 0; j < c1; ++j) { printf("Enter element matrix1[%d][%d]: ", i + 1, j + 1); scanf("%d", &matrix1[i][j]); } } // Step 5: Input elements for the second matrix printf("\nEnter elements of second matrix:\n"); for (i = 0; i < r2; ++i) { for (j = 0; j < c2; ++j) { printf("Enter element matrix2[%d][%d]: ", i + 1, j + 1); scanf("%d", &matrix2[i][j]); } } // Step 6: Initialize result matrix with zeros for (i = 0; i < r1; ++i) { for (j = 0; j < c2; ++j) { resultMatrix[i][j] = 0; } } // Step 7: Perform matrix multiplication // Outer loops iterate through rows of result matrix (r1) and columns of result matrix (c2) for (i = 0; i < r1; ++i) { // rows of first matrix for (j = 0; j < c2; ++j) { // columns of second matrix // Innermost loop calculates the sum of products for each element of the result matrix for (k = 0; k < c1; ++k) { // columns of first matrix OR rows of second matrix resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j]; } } } // Step 8: Display the result matrix printf("\nResultant matrix after multiplication:\n"); for (i = 0; i < r1; ++i) { for (j = 0; j < c2; ++j) { printf("%d ", resultMatrix[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS