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

Exploring Two-Dimensional Arrays in C

👁 93 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

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

                        

🖥 Program 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

                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.