Multidimensional arrays

Passing objects in the x axis and y axis is nothing but a multidimensional array. The where the x axis is the row, and the y axis is the column of the matrix in which the array values are given. Multi in this case means we are viewing arrays from the multi-corner perspectives; this is called a multidimensional array. The following is a multidimensional array we have created to explain this concept:

2  4  5
3 4 7
5 2 1

This is a matrix and it has three rows and three columns. 2 is in the zero row and zero column, and the 4 beside it is in the zero row and first column, and the same iteration for the rest of the values. So each argument has an x axis and a y axis.

Let's take an example to explain this. We will create another class, name it Multidimensional.java, and declare a multidimensional array, a, in it:

int a[][] = new int[2][3];

The first bracket represents the x axis or rows, and the second represents the y axis or columns. So, the x axis takes three values, which means three rows and the y axis takes three columns. We then assign the values for each element of the matrix that we created to explain multidimensional arrays. The following code shows how to assign values for the matrix:

a[0][0]=2;
a[0][1]=4;
a[0][2]=5;
a[1][0]=3;
a[1][1]=4;
a[1][2]=7;

This way we will feed all the values into a multidimensional array. If we want to display the value of the second row, first column, we write a print statement and give the location of the element whose value we wish to display. In this case, we want to display the second row, first column, so the print statement will be written as:

System.out.println(a[1][0]);

The print statement will display 3, which is the value of the element in that location. In the next section, we will take an example that will help explain how we use all these concepts in solving coding.

How do we print all the values of the a array that we declared in this example? In the earlier example, we printed the array by simply creating a for loop, iterated it from 0 to the length of the array, and the array was displayed.

If we want to declare a multidimensional array in the simplest format, like how array b was described in the previous example, we could write it in the following manner:

int b[][]= {{2,4,5},{3,4,7},{5,2,1}};

The array will assume that the values in the first bracket are in the zero index, the second in the first index, and the third in the second index. This is the simplest way to declare multidimensional arrays.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.240.21