2-D Array in C
In C programming, a 2D array, also known as a two-dimensional array, is a collection of elements organized in a grid-like structure with rows and columns. It is a matrix-like data structure where elements are accessed using two indices: one for the row and one for the column.
To declare and use a 2D array in C, you typically follow these steps:
1. Array Declaration:
- Specify the data type of the elements in the array.
- Provide a name for the array.
- Use square brackets `[][]` to indicate that it is a 2D array.
- Specify the size of the array by indicating the number of rows and columns it should have. Syntax:
data_type array_name[rows][columns];
Example
int matrix[3][4]; // Declaration of a 2D integer array with 3 rows and 4 columns
float table[2][2]; // Declaration of a 2D float array with 2 rows and 2 columns
2. Array Initialization (optional)
- Assign initial values to the elements of the array.
- This step is not mandatory. If not initialized explicitly, the elements will have default values (e.g., 0 for integers, 0.0 for floats, NULL for pointers).
data_type array_name[rows][columns] = {
{value1, value2, ...},
{value1, value2, ...},
...
};
Example
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
}; // Initialization of a 2D integer array
float table[2][2] = {
{1.5, 2.3},
{3.7, 4.2}
}; // Initialization of a 2D float array
3. Array Access
- Access individual elements of the array using their row and column indices.
- Indices start from 0 and go up to `rows - 1` for the row index and `columns - 1` for the column index.
array_name[row_index][column_index]
Example
int value = matrix[1][2]; // Accessing the element in the 2nd row and 3rd column
printf("%d\n", value); // Output: 7
matrix[2][1] = 15; // Modifying the element in the 3rd row and 2nd column
4. Array Iteration
- Use nested loops (e.g., two `for` loops) to iterate over the 2D array elements.
- The outer loop controls the row index, and the inner loop controls the column index.
- Access each element using its row and column indices within the loop body.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
2D arrays are commonly used to represent matrices, tables, grids, and other tabular structures in C. They provide a convenient way to store and process data organized in rows and