Two Dimensional Array in C
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to any number of functions wherever required.
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
Consider the following example.
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array in C
In the 1D array, we don’t need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two-dimensional array can be declared and defined in the following way.
Two-dimensional array example in C
Output
arr[0][0] = 1 arr[0][1] = 2 arr[0][2] = 3 arr[1][0] = 2 arr[1][1] = 3 arr[1][2] = 4 arr[2][0] = 3 arr[2][1] = 4 arr[2][2] = 5 arr[3][0] = 4 arr[3][1] = 5 arr[3][2] = 6
C 2D array example: Storing elements in a matrix and printing it.
Output
Enter a[0][0]: 56 Enter a[0][1]: 10 Enter a[0][2]: 30 Enter a[1][0]: 34 Enter a[1][1]: 21 Enter a[1][2]: 34 Enter a[2][0]: 45 Enter a[2][1]: 56 Enter a[2][2]: 78 printing the elements .... 56 10 30 34 21 34 45 56 78