An array of arrays is called a multidimensional array. Let’s start with a simple two dimensional array.
A two dimensional array is defined as follows:
DataType[][] arr;
For example:
int[][] iArray;
To initialize a multidimensional array, place each array within its own set of brackets:
int[][] iArray={ {2,3,6} , {6,2,9} };
The above array is a two dimensional array. Actually, it is an array that contains two one dimensional arrays.
A two dimensional array can also be initialized as empty by giving the size. It goes like this:
int[][] iArray = new int[2][3];
The elements of array can be stored/retrieved using the corresponding indices. For example, to initialize all the elements of the above array, you will do this:
iArray[0][0]=2;
iArray[0][1]=3;
iArray[0][2]=6;
iArray[1][0]=6;
iArray[1][1]=2;
iArray[1][2]=9;
Remember! The maximum index is one less than the size just because we start counting from zero.
Now let’s jump to three dimensional arrays. You create a three dimensional array like this:
int[][][] array=new int[5][5][5];
OR like this if you want to initialize it too.
int[][][] array= {
{ {2,3,5} , {1,2,3} } ,
{ {4,5,6} , {7,8,9} } ,
{ {3,2,1} , {9,8,7} }
};
//The code is written in multiple lines to make it easy to read
We use triple nested loops to access a three dimensional array:
//Do not worry if you do not understand the concept of triple nested loop
//You will understand it later
Practice Corner:
- Write a program to declare and initialize a two dimensional array. Then find the sum of all the elements in the array.
Johnson
8