Multidimensional Arrays (Lesson-22)

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:



Remember! The maximum index is one less than the size just because we start counting from zero.

*See the above two questions and comment the answer
**The above two questions are taken from

We usually use nested loops to access multidimensional arrays. Consider the following program to create a two dimensional array and display it on the screen.

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.

Post a Comment