next up previous contents
Next: 5 More advanced input Up: 4 Arrays, nested loops Previous: Composite operators   Contents

Multi-dimensional arrays and nested loops

It is also possible to create arrays with two or more dimensions. Two dimensional arrays are useful for storing matrices for example. In Java, arrays of more than one dimension are created by making arrays of arrays. This is known as nesting. The follow examples should make this more clear.

// two ways of creating two dimensional arrays
int[][] matrix = {{0, 1, 2, 3},
                  {4, 5, 6, 7},
                  {8, 9, 10, 11}};

int[][] square = new int[5][5];    // creates 5 by 5 matrix with zero values

Taking the above 2D array matrix as an example, in order to perform operations on each value of a multi-dimensional array, it is necessary to nest several for loops. The example code below sets every entry of matrix to 1.

for (int i=0; i<3; i++)
{
    for (int j=0; j<4; j++)
    {
        matrix[i][j] = 1;
    }
}

You can think of the outer loop (i) moving down the rows of matrix, then the inner loop (j) moves along each row. Note that when you nest loops, the loop variable of each loop (i and j in the example above) must be different for this to work properly.

Particularly with two dimensional arrays such as matrices, it can be helpful to print the entries to screen in columns and lines as they would normally appear in a matrix. Firstly creative use of System.out.println() and System.out.print() (the latter does not move to the next line after printing the output) can help. Secondly there are some special characters: "\t", which produces a tab and "\n" which moves to the next line. These can be included anywhere in a string.

Exercise 4.3


(10 marks)



Write a program that will multiply together two 3 x 3 matrices (as defined below) with integer entries and print the resulting 3 x 3 matrix to the screen, making use of nested for loops, and the += composite operator. Use "\t" to help format the output. Include the program listing and output in your lab book. You can check the answer by hand or ask a demonstrator to check that it is correct.

  int[][] matrixA = { { 1, 0, 1 },
                      { 1, 2, 3 },
                      { 1, 4, 5 } };

  int[][] matrixB = { { 5, 4, 0 },
                      { 4, 8, 1 },
                      { 1, 1, 0 } };

Hint: carefully analyse how matrix multiplication works before you write your program. Show this analysis in your lab book to justify your program design.




next up previous contents
Next: 5 More advanced input Up: 4 Arrays, nested loops Previous: Composite operators   Contents
RHUL Dept. of Physics