C++

Multidimensional Arrays

It is possible to have arrays of more than one dimension. Each dimension is represented as a subscript in the array. Therefore, a two-dimensional array has two subscripts; a three-dimensional array has three subscripts; and so on. Arrays can have any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

A good example of a two-dimensional array is a chess board. One dimension represents the eight rows; the other dimension represents the eight columns. Figure 11.3 illustrates this idea.

Suppose that you have a class named SQUARE. The declaration of an array named Board that represents it would be

SQUARE Board[8][8];

You could also represent the same data with a one-dimensional, 64-square array. For example,

SQUARE Board[64]

This doesn’t correspond as closely to the real-world object as the two-dimension. When the game begins, the king is located in the fourth position in the first row. Counting from zero array, that position corresponds to

Board[0][3];

assuming that the first subscript corresponds to row, and the second to column. The layout of positions for the entire board is illustrated in Figure 11.3.

11.3.JPG (19435 bytes)
Figure 11.3.
A chess board and a two-dimensional array.

Back to Index