- A 2-dimensional array in C is an array of arrays.
- It allows you to store and access elements in a tabular format with rows and columns.
- The elements in a 2D array are typically referred to using two indices, representing the row and column positions.
Here’s the general syntax for declaring and initializing a 2D array in C:
C
datatype arrayName[rowSize][columnSize];
Here’s an example of declaring and initializing a 2D array of integers:
C
int matrix[3][4]; // 3 rows and 4 columns
You can also initialize the elements of a 2D array during declaration:
C
int matrix[3][4] = {
{1, 2, 3, 4}, // first row
{5, 6, 7, 8}, // second row
{9, 10, 11, 12} // third row
};
To access individual elements in a 2D array, you use the row and column indices:
C
int element = matrix[rowIndex][columnIndex];
Here’s an example that demonstrates accessing and modifying elements in a 2D array:
C
#include <stdio.h>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("Element at matrix[1][2]: %d\n", matrix[1][2]); // Accessing element
matrix[1][2] = 99; // Modifying element
printf("Modified element at matrix[1][2]: %d\n", matrix[1][2]);
return 0;
}
In this example,
- We declared and initialized a 2D array called matrix with 3 rows and 4 columns.
- We then accessed the element at matrix[1][2] (which is 7) and modified it to 99.
- Finally, we printed the modified element.
Remember that the indices in a 2D array start from 0. The first index represents the row number, and the second index represents the column number.