Programming Example
Exploring Two-Dimensional Arrays in C
Study this program carefully to understand the logic, output, and explanation in a structured way.
// 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 read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.