C - Reading and Displaying Elements from a 2D Array

Here's an example of how to read and display elements from a two-dimensional (2D) array in C:

Source Code:


#include <stdio.h>

int main() {
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    printf("2D Array (Matrix):\n");

    // Reading and displaying elements of the 2D array
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%2d ", matrix[i][j]);
        }
        printf("\n"); // Move to the next row after printing each row
    }

    return 0;
}
    

Explanation:

  1. Declaration and Initialization:

    We declare and initialize a 3x3 2D array called matrix with integer values.

  2. Reading and Displaying Elements:

    We use nested loops to iterate through the rows and columns of the 2D array. The outer loop (controlled by i) iterates over the rows, and the inner loop (controlled by j) iterates over the columns.

    Inside the nested loops, we use matrix[i][j] to access each element of the 2D array based on its row and column indices.

    We use printf to display the elements. The format specifier %2d is used to print each integer with a minimum width of 2 characters, which aligns the columns neatly.

    After printing each row, we use printf("\n") to move to the next line and display the next row of the 2D array.

Output:

2D Array (Matrix):
 1  2  3 
 4  5  6 
 7  8  9