C Online Compiler
Example: Matrix Addition in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Addition #include <stdio.h> int main() { int rows, cols; // Step 1: Get matrix dimensions from the user printf("Enter the number of rows: "); scanf("%d", &rows); printf("Enter the number of columns: "); scanf("%d", &cols); // Step 2: Declare two matrices and a result matrix // Using variable length arrays (VLA) available in C99, // otherwise, fixed-size arrays or dynamic allocation would be needed. int matrix1[rows][cols]; int matrix2[rows][cols]; int sumMatrix[rows][cols]; // Step 3: Input elements for the first matrix printf("\nEnter elements of first matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element matrix1[%d][%d]: ", i, j); scanf("%d", &matrix1[i][j]); } } // Step 4: Input elements for the second matrix printf("\nEnter elements of second matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element matrix2[%d][%d]: ", i, j); scanf("%d", &matrix2[i][j]); } } // Step 5: Perform matrix addition printf("\nPerforming Matrix Addition...\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } // Step 6: Display the sum matrix printf("\nSum of the two matrices:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d\t", sumMatrix[i][j]); } printf("\n"); // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS