What is a 2D Array?
Definition:
A 2D array is an array of arrays, used to store data in rows and columns.
Example use cases:
- Marks of students (rows = students, columns = subjects)
- Matrices
- Tables
1. Syntax of a 2D Array
data_type array_name[rows][columns];Example:
int a[3][4];- 3 rows
- 4 columns
- Total elements = 3 × 4 = 12
2. Visual Representation (Important)
Imagine this array:
int a[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};It looks like a table:
| Col 0 | Col 1 | Col 2 | |
| Row 0 | 1 | 2 | 3 |
| Row 1 | 4 | 5 | 6 |
| Row 2 | 7 | 8 | 9 |
a[0][0] = 1a[1][2] = 6a[2][1] = 8
3. How Indexing Works
a[row][column]- First index → row
- Second index → column
- Index always starts from 0
4. Initializing a 2D Array
Method 1: Full initialization
int a[2][3] = {
{10, 20, 30},
{40, 50, 60}
};Method 2: Inline initialization
int a[2][3] = {10, 20, 30, 40, 50, 60};5. Accessing Elements
printf("%d", a[1][2]);Output:
60Because row 1, column 2 contains 60.
