What is Two Dimensional Array in C?
Array with two subscripts is known as two dimensional Array. The 2D array is organized as the collection of rows and columns to form a matrix. 2D arrays are created to manipulate data structures.
Example: int arr[][];
Declaration of 2D array.
The following shows the syntax for declaring 2D Array.
1 | data_type array_name[rows][columns]; |
The data-type must be a valid C data type, a unique name must be specified to each array and the arraySize must be of an integer constant. The 2D array is considered as the table with a specified number of rows and columns.
Consider the following example of 2D integer type array with 5 rows and 3 columns:
1 | int arr[5][3]; |
Initialization of 2D array.
2D array is initialized using the curly braces {}. Such as:
1 2 3 4 5 6 7 8 9 10 | //initializing with 5 rows and 3 columns int arr[5][3] = { {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {7, 8, 9} }; OR int arr[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11} |
Accessing Two-Dimensional Array Elements in C
An array can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket [][]. Such as:
1 2 3 4 | arr[2][3]; //the 4th element of the third row is accessed arr[3][2]; //the 3rd element of the fourth row is accessed OR int val = arr[2][3]; // assigning the element to val |
Example of 2D Array in C.
Displaying the elements with index number from 2D Arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> int main() { //Array with 4 rows and 2 columns int arr[4][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 }, { 6, 7 } }; int i, j; //Displaying the elements printf("Elements with index numbers:\n"); for (i = 0; i < 4; i++) { for (j = 0; j < 2; j++) { printf("a[%d][%d] = %d\n", i, j, arr[i][j]); } } return 0; } |
Output: After executing the above code, the following result will be displayed.
1 2 3 4 5 6 7 8 | arr[0][0]: 0 arr[0][1]: 1 arr[1][0]: 2 arr[1][1]: 3 arr[2][0]: 4 arr[2][1]: 5 arr[3][0]: 6 arr[3][1]: 7 |