C Online Compiler
Example: Matrix Multiplication User Input in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Multiplication User Input #include <stdio.h> #define MAX_SIZE 10 // Maximum size for matrix dimensions int main() { int row1, col1, row2, col2; int matrix1[MAX_SIZE][MAX_SIZE]; int matrix2[MAX_SIZE][MAX_SIZE]; int result[MAX_SIZE][MAX_SIZE]; // Step 1: Get dimensions for Matrix 1 from user printf("Enter dimensions for Matrix 1 (rows columns): "); scanf("%d %d", &row1, &col1); // Step 2: Get dimensions for Matrix 2 from user printf("Enter dimensions for Matrix 2 (rows columns): "); scanf("%d %d", &row2, &col2); // Step 3: Check for valid multiplication dimensions if (col1 != row2) { printf("Error: Matrices cannot be multiplied. Number of columns in Matrix1 must equal number of rows in Matrix2.\n"); return 1; } // Step 4: Get elements for Matrix 1 from user printf("Enter elements for Matrix 1 (%dx%d):\n", row1, col1); for (int i = 0; i < row1; i++) { for (int j = 0; j < col1; j++) { printf("Enter element matrix1[%d][%d]: ", i, j); scanf("%d", &matrix1[i][j]); } } // Step 5: Get elements for Matrix 2 from user printf("Enter elements for Matrix 2 (%dx%d):\n", row2, col2); for (int i = 0; i < row2; i++) { for (int j = 0; j < col2; j++) { printf("Enter element matrix2[%d][%d]: ", i, j); scanf("%d", &matrix2[i][j]); } } // Step 6: 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 7: Perform matrix multiplication (same logic as Approach 1) for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) { for (int k = 0; k < col1; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } // Step 8: Print the result matrix printf("\nResultant 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