2-D Array in C
A two-dimensional (2D) array is an arrangement of items in C that are arranged in a grid and are individually identified by a pair of indices: a row index and a column index. A 2D array can be compared to a table or matrix that has rows and columns. A 2D array in C is declared, initialised, and used as follows:
Declaration:
data_type array_name[row_size][column_size];
1. data_type
: The data type of the elements in the array (e.g.,int
,double
,char
, etc.).2. array_name
: The name of the array.3. row_size
: The number of rows in the array.4. column_size
: The number of columns in the array.
Initialization: You can initialize a 2D array when declaring it, or you can assign values to individual elements later in your code.
Here's an example of declaring and initializing a 2D integer array:
int a[2][2];
Accessing Elements: You can access individual elements of a 2D array using the row and column indices. The indices are zero-based, meaning the first row and first column have index 0.
Example: Here's a complete example of declaring, initializing, and accessing elements in a 2D array:
In this example, we declare and initialize a 2x2 integer array called matrix
and then access individual elements using their indices.
Remember that when working with 2D arrays in C, you need to be mindful of array bounds to avoid accessing elements outside the valid range, which can lead to undefined behavior.