Exploring Two-Dimensional Arrays in C

Data Structure Array (Article) Array (Program)

73

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:

#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

This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.