// Declare a 2D array
int matrix[3][4] = {
{10, 20, 30, 40},
{50, 60, 70, 80},
{90, 100, 110, 120}
};
Elements of the 2D array (matrix): 10 20 30 40 50 60 70 80 90 100 110 120 Sum of all elements in the matrix = 940
#include <stdio.h>
int main() {
int rows = 3;
int cols = 4;
// Declare a 2D array
int matrix[3][4] = {
{10, 20, 30, 40},
{50, 60, 70, 80},
{90, 100, 110, 120}
};
// Display the 2D array
printf("Elements of the 2D array (matrix):\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d", matrix[i][j]);
}
printf("\n");
}
// Find sum of all elements
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum += matrix[i][j];
}
}
printf("\nSum of all elements in the matrix = %d\n", sum);
return 0;
}
Elements of the 2D array (matrix):
10 20 30 40
50 60 70 80
90 100 110 120
Sum of all elements in the matrix = 940
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.