Chapter 7 Multidimensional Arrays
Defining a two dimensional array elementType[][] arrayName; // Java pro elementType arrayName[][]; // C++ alternate For example: int[][] chessboard; To allocate space for the array, use new: chessboard = new int[8][8]; Or int[][] chessboard = new int[8][8];
Accessing elements int king = 10; chessboard[0][4] = king; int piece = chessboard[7][3]; Each dimension must use a pair of brackets around the index [] Do not try chessboard[7, 3] notation
Initializing multiple dimensions
What’s an array? A two-dimensional array is actually a one- dimensional array where each element is a one-dimensiona array An “array of arrays” is an important concept! Each array has its own length property Array lengths can be different (ragged array)
The length property in action
Rectangular versus ragged arrays A rectangular array has the same number of elements in each array for a given dimension int[][] myArray = new int[5][7]; myArray has 5 x 7 = 35 elements, with 7 elements in each of the 5 rows A ragged array has varying numbers of elements in a given dimension, as illustrated on the next slide:
Ragged array definition
The contents of a ragged array
Another array initialization example
Passing a two-dimensional array as an argument to a method
Multiple Dimensional Arrays An array of arrays of arrays of…. Each dimension can consist of rectangular or ragged arrays Each dimension is enclosed with a pair of brackets Maximum number of dimensions is nominally 255 for the VM*
Three-dimensional ragged array
Lab 2 Write a program to create a chessboard stored as a two-dimensional character array Chess is played on an 8 x 8 square board with a total of 64 squares Empty squares can be represented by a space Abbreviate pieces as ‘R’ = rook, ‘N’ = knight, ‘B’ = Bishop, ‘Q’ = queen, ‘K’ = king, ‘P’ = pawn Initialize the array according to the diagram
What the array dimensions mean The columns will be the first array dimension Label columns ‘a’ – ‘h’ Column a is the 0 index, h is the 7 index The rows will be the second array dimension Number rows 1-8 Row 1 is the 0 index, 8 is the 7 index
What to do and turn in Write a method that creates a two- dimensional character array, initializes it with the starting chessboard as shown in the diagram, and returns the array Write a method that prints the chess board contents and the row/column labels Turn in a screen shot of the chess board Turn in a print-out of your program
What the chessboard looks like:
Extra Credit (10%) Write a user interface that makes a move The notation is the letter/number of the start location and the letter/number of the end location (e.g. “d1 g4” would move the white queen diagonally 3 squares) Allow any move (don’t check legality) Print an updated view of the board showing the pieces after the move