C Online Compiler
Example: Matrix Multiplication with Compatibility Check in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Multiplication with Compatibility Check #include <stdio.h> #define MAX_DIM 10 // Define a maximum dimension for matrices // Function to read matrix elements void readMatrix(int matrix[MAX_DIM][MAX_DIM], int rows, int cols) { printf("Enter elements:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element [%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } } } // Function to print matrix elements void printMatrix(int matrix[MAX_DIM][MAX_DIM], int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } } int main() { int mat1[MAX_DIM][MAX_DIM], mat2[MAX_DIM][MAX_DIM], result[MAX_DIM][MAX_DIM]; 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 compatibility for multiplication if (c1 != r2) { printf("Error: Matrices are not compatible for multiplication.\n"); printf("Number of columns in first matrix must be equal to number of rows in second matrix.\n"); return 1; // Indicate an error } // Step 4: Read elements for the first matrix printf("\n--- Enter elements for First Matrix (%dx%d) ---\n", r1, c1); readMatrix(mat1, r1, c1); // Step 5: Read elements for the second matrix printf("\n--- Enter elements for Second Matrix (%dx%d) ---\n", r2, c2); readMatrix(mat2, r2, c2); // Step 6: Perform matrix multiplication // The resulting matrix will have dimensions r1 x c2 for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { result[i][j] = 0; // Initialize element to 0 for (int k = 0; k < c1; k++) { // Or k < r2, since c1 == r2 result[i][j] += mat1[i][k] * mat2[k][j]; } } } // Step 7: Display the matrices and their product printf("\n--- First Matrix ---\n"); printMatrix(mat1, r1, c1); printf("\n--- Second Matrix ---\n"); printMatrix(mat2, r2, c2); printf("\n--- Product of Matrices (%dx%d) ---\n", r1, c2); printMatrix(result, r1, c2); return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS