What is 2D Array in C: Explanation and Example
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.
#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; }
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.