Prelab 5: Java Arrays

Reading

2D arrays

Arrays with multiple dimensions may be declared and used in Java. Two-dimensional (2D) arrays are useful when data can be represented by a grid of fixed size. 2D arrays are often used to represent tables, images, and game boards. Checkers, chess, tic-tac-toe, crosswords and mazes are examples of games that could be implemented using a 2D array.

In Lab 5 you will implement a game using a 2D array, so it is important to understand how array elements are accessed and their values are manipulated. We can declare an 2D array of boolean values named gameboard with 8 rows and 8 columns with the Java statement

boolean[][] gameboard = new boolean[8][8];

The number of pairs of square brackets indicates the dimension of the array. In a 2D Java array, the number in the first pair of brackets indicates the row and the second the column. A 2D array is basically a 1D array of 1D arrays, i.e. its rows. The number of rows in our 2D array gameboard is given by gameboard.length. The i-th row of gameboard is the 1D array gameboard[i], and its length (or the number of columns) is gameboard[i].length.

If we want to initialize all values of the array to false, we execute the following statements:

for( int i=0; i<gameboard.length; i++ ) { for( int j=0; j<gameboard[i].length; j++ ) { gameboard[i][j] = false; } }

We can visualize our gameboard array as a 8×8 grid of squares, where the top left square corresponds to element gameboard[0][0] and the bottom right square corresponds to element gameboard[7][7].

Question 1: Assume we have initialized all the elements of gameboard to false. Consider the following Java statements: for( int i=1; i<7; i++ ) { gameboard[i][3] = true; gameboard[i][4] = true; } for( int j=2; j<6; j++ ) { gameboard[3][j] = true; gameboard[4][j] = true; }

Color the squares in the grid below corresponding to the elements of gameboard whose values are now true.

For any row r and column c such that 0<r<7 and 0<c<7 we can specify the north, south, east and west neighbors of element gameboard[r][c] as follows:

gameboard[r-1][c] (north neighbor)
gameboard[r+1][c] (south neighbor)
gameboard[r][c-1] (west neighbor)
gameboard[r][c+1] (east neighbor)

Question 2: For any row r and column c such that 0<r<7 and 0<c<7, how would you identify the northeast, northwest, southeast and southwest neighbors of element gameboard[r][c]?

Question 3: Why do we specify the constraints 0<r<7 and 0<c<7 when referring to the neighbors of gameboard[r][c]?