Two-dimensions array
Two-dimensions array
Two-dimension arrays are nothing but the arrays as elements of one array.rather then storing the data if we store the arrays in elements then it becomes 2D array. 2D arrays are also similar to the matrix.
Declaration of 2D array:
Declaration of 2D arrays is quite similar to declaring the one-dimension array, here we also need to specify the size of the second array.
syntax:
data_type name_of_array [ size_of_raw ][ size_of_colomn ];
example:
int arr[ 2 ] [ 2 ]; it declare 2 X 2, 2-D array.
int arr [ 3 ][ 2 ]; its declare 3 X 2, 2-D array.
Declaration of 2D array with initializing elements:
1 int arr[ 3 ][ 4 ] = { {0 ,1, 2, 3}, { 4, 5, 6, 7}, { 8, 9, 10, 11} };
This method first declares the 3 X 4 array then assign value to them according to the position.in this case arr[ 0 ][ 0 ] to arr [ 0 ][ 3 ] is assigned as 0,1,2,3 then
arr[ 1 ][ 0 ] to arr [ 1 ][ 3 ] is assigned as 4, 5, 6, 7 and
arr[ 1 ][ 0 ] to arr [ 1 ][ 3 ] is assigned as 8, 9, 10, 11.
we can also diclare an array as below and it done same work as above.
int arr [ 3 ][ 4 ] = { 0 ,1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
2 int arr [ 3 ][ 4 ] = { 0 ,1, 2, 3, 4, 5, 6, 7, 8 };
now in this case same as one diamention array the value are assign as per the index an other elements of 2D array is assign as 0.
so in this case first declares the 3 X 4 array then assign value to them according to the position.here
arr[ 0 ][ 0 ] to arr [ 0 ][ 3 ] is assigned as 0,1,2,3 then
arr[ 1 ][ 0 ] to arr [ 1 ][ 3 ] is assigned as 4, 5, 6, 7 and
arr[ 1 ][ 0 ] to arr [ 1 ][ 3 ] is assigned as 8, 0, 0, 0.
Initializing elements of 2d array:
As we initialize one dimension array, we can also initialize a 2D array by the using element's index in an array.
int arr[ 3 ][ 4 ];
arr[ 0 ][ 0 ] = 10;
arr[ 0 ][ 1 ] = 21;
arr[ 0 ][ 2 ] = 7;
arr[ 3 ][ 0 ] = arr[ 0 ][ 1 ] ;
arr[ 3 ][ 1 ] =arr[ 0 ][ 1 ] ;
and so on...
Multidimension array
we can declare nth dimension array we just need to give that much of sizes in the braces for creating that dimension array.
data_type array_name[ n1 ][ n2 ][ n3 ][ n4 ]...[ nm ];
we can assess and initialize the array as we did in the case of 2D array.
Let's declare a 3D array and initialize it.
int arr[ 3 ][ 3 ][ 2 ] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,18}
we can also declare same array as below it is easy to understand.
int arr[ 3 ][ 3 ][ 2 ] ={
{{1, 2}, {3, 4}, {5, 6}},
{{7, 8}, {9, 10}, {11, 12}},
{{13, 14}, {15, 16}, {17,18}}
}