Two Dimensional Arrays
It is also possible to have two or more dimensions. The two-dimension array is also known as a matrix. It can be thought as a rectangular display of elements with row and columns. It uses two brackets. For example int mat[4][4].
Array elements in matrix form:
|
Col 1
|
Col 2
|
Col 3
|
Col 4
|
Row1
|
mat[0][0]
|
mat[0][1]
|
mat[0][2]
|
mat[0][3]
|
Row2
|
mat[1][0]
|
mat[1][1]
|
mat[1][2]
|
mat[1][3]
|
Row3
|
mat[2][0]
|
mat[2][1]
|
mat[2][2]
|
mat[2][3]
|
Row4
|
mat[3][0]
|
mat[3][1]
|
mat[3][2]
|
mat[3][3]
|
The two-dimensional array is a collection of a number of one-dimensional arrays.
Initializing a Two Dimensional Arrays
The initialization of two dimensional arrays is as follows:
int arr[3][2] = {
{ 4, 6 },
{ 6, 1 },
{ 7, 4 }
};
or we can initialize as-
int arr[3][2] = { 4,6,6,1,7,4};
Note: It is necessary to mention the second (Column) dimension, whereas the first dimension (Row) is optional. So
int arr[][2] = {4,6,6,1,7,4};
is a correct statement, but
int arr[3][] = {4,6,6,1,7,4};
is incorrect.