0
0
CConceptBeginner · 3 min read

What is 2D Array in C: Explanation and Example

A 2D array in C is like a table with rows and columns, used to store data in a grid form. It is declared as an array of arrays, for example, int arr[3][4] creates 3 rows and 4 columns of integers.
⚙️

How It Works

A 2D array in C is like a grid or a spreadsheet where data is arranged in rows and columns. Imagine a chessboard where each square can hold a value; similarly, a 2D array holds values at positions identified by two indexes: one for the row and one for the column.

When you declare a 2D array, you specify how many rows and columns it has. For example, int arr[3][4] means there are 3 rows and 4 columns, making 12 elements in total. The computer stores these elements in a continuous block of memory, row by row.

You access or change a value by giving its row and column number, like arr[1][2] which means the element in the second row and third column (counting from zero).

💻

Example

This example shows how to declare, assign, and print a 2D array of integers in C.

c
#include <stdio.h>

int main() {
    int arr[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Output
1 2 3 4 5 6
🎯

When to Use

Use 2D arrays when you need to store data in a grid-like structure, such as tables, matrices, or game boards. For example, you can use a 2D array to represent a calendar, a pixel grid in an image, or a seating chart.

They are helpful when you want to organize data with two dimensions and access elements by row and column indexes quickly.

Key Points

  • A 2D array is an array of arrays, storing data in rows and columns.
  • Elements are accessed using two indexes: row and column.
  • Memory is stored row-wise in C.
  • Useful for representing grids, tables, and matrices.

Key Takeaways

A 2D array stores data in a grid with rows and columns using two indexes.
Declare a 2D array with syntax like int arr[rows][columns].
Access elements by specifying row and column positions, starting at zero.
2D arrays are ideal for tables, matrices, and grid-based data.
Memory for 2D arrays in C is stored row by row continuously.