Home / Programs / Exploring Two-Dimensional Arrays in C
Programming Example

Exploring Two-Dimensional Arrays in C

👁 93 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Given Input:

// Declare a 2D array
    int matrix[3][4] = {
        {10, 20, 30, 40},
        {50, 60, 70, 80},
        {90, 100, 110, 120}
    };

Expected Output:

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

Program Code

#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;
}

Output

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

How to learn from this program

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.