C Online Compiler
Example: Addition of Two Matrices in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Addition of Two Matrices #include <stdio.h> int main() { int rows, cols; int matrix1[10][10], matrix2[10][10], sumMatrix[10][10]; int i, j; // Step 1: Get dimensions from the user printf("Enter the number of rows (max 10): "); scanf("%d", &rows); printf("Enter the number of columns (max 10): "); scanf("%d", &cols); // Validate dimensions (optional, but good practice) if (rows <= 0 || rows > 10 || cols <= 0 || cols > 10) { printf("Invalid dimensions. Rows and columns must be between 1 and 10.\n"); return 1; // Indicate an error } // Step 2: Get elements for the first matrix printf("\nEnter elements of first matrix:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("Enter element matrix1[%d][%d]: ", i, j); scanf("%d", &matrix1[i][j]); } } // Step 3: Get elements for the second matrix printf("\nEnter elements of second matrix:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("Enter element matrix2[%d][%d]: ", i, j); scanf("%d", &matrix2[i][j]); } } // Step 4: Perform matrix addition for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } // Step 5: Display the resultant sum matrix printf("\nSum of the two matrices:\n"); for (i = 0; i < rows; i++) { for (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