Part 12

Multidimensional data

Previously we have used one dimensional arrays, where the index tells us the location of a value in the only dimension. We can also create multidimensional arrays. Then we need the indexes of a value in each dimension to access the value. This comes handy when our data is multidimensional, for example when dealing with coordinates.

A two dimensional array with two rows and three columns can be created like so:

int rows = 2;
int columns = 3;
int[][] twoDimensionalArray = new int[rows][columns];

In the array we created above, each row refers to an array with a certain number of columns. We can iterate over a two dimensional array using two nested for loops like so:

int rows = 2;
int columns = 3;
int[][] twoDimensionalArray = new int[rows][columns];

System.out.println("row, column, value");
for (int row = 0; row < twoDimensionalArray.length; row++) {
    for (int column = 0; column < twoDimensionalArray[row].length; column++) {
        int value = twoDimensionalArray[row][column];
        System.out.println("" + row + ", " + column + ", " + value);
    }
}

The program output is as follows:

Sample output

row, column, value 0, 0, 0 0, 1, 0 0, 2, 0 1, 0, 0 1, 1, 0 1, 2, 0

We can see that the default value of variables type int is 0.

We can change the values in the array just like before. Below we set new values to three elements of the array.

int rows = 2;
int columns = 3;
int[][] twoDimensionalArray = new int[rows][columns];

twoDimensionalArray[0][1] = 4;
twoDimensionalArray[1][1] = 1;
twoDimensionalArray[1][0] = 8;

System.out.println("row, column, value");
for (int row = 0; row < twoDimensionalArray.length; row++) {
    for (int column = 0; column < twoDimensionalArray[row].length; column++) {
        int value = twoDimensionalArray[row][column];
        System.out.println("" + row + ", " + column + ", " + value);
    }
}

The program output is as follows:

Sample output

row, column, value 0, 0, 0 1, 0, 4 2, 0, 0 0, 1, 8 1, 1, 1 2, 1, 0

Loading
Loading
You have reached the end of this section! Continue to the next section:

Remember to check your points from the ball on the bottom-right corner of the material!