C Online Compiler
Example: Matrix Addition using Arrays in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Addition using Arrays #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); // Declare three 2D arrays (matrices) int matrix1[rows][cols]; int matrix2[rows][cols]; int sumMatrix[rows][cols]; // Step 2: Input elements for the first matrix printf("\nEnter elements for Matrix 1:\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 3: Input elements for the second matrix printf("\nEnter elements for Matrix 2:\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 4: Perform matrix addition // Iterate through each element and add corresponding elements for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } // Step 5: Display the result (sumMatrix) printf("\nSum of the 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