Saturday, December 26, 2009

Multidimensional Arrays

So far, the arrays in this chapter have been one-dimensional arrays--that is, they are a one-row collection of variables, however, you can create arrays that have up
to 60 dimensions. Usually, two-dimensional arrays will suffice for most introductory programming projects, and most likely you won't need to make an array of more than three dimensions.

Think of a two-dimensional array as a tic-tac-toe board--a set of columns and rows that intersect to form a grid. Each grid cell has a location defined as ColumnNumber, RowNumber. Each element is defined by the coordinates of the column position and the row position. For example, the array element iVar(0, 0) is 5 and the element iVar(2,2) is 49.
To create a two-dimensional array, use the following syntax:

Dim|Public|Private ArrayName(SubscriptOfCols, _
SubscriptOfRows) As DataType

In this syntax,

Dim, Public, and Private are Visual Basic keywords that declare the array and its scope. If you use Dim, the array is private to the procedure in which it's declared. Public makes the array visible from
anywhere in the program, and Private (within a form or module's General section) makes the array visible only to the form or module in which it's declared. Using Dim within a module automatically
makes the array available anywhere in the program, as if the Public keyword were used.

ArrayName is the name of the array.

SubscriptOfCols is the number of the highest column in the array.

SubscriptOfRows is the number of the highest row in the array.

As is the Visual Basic keyword that denotes type declaration.

DataType is any valid Visual Basic data type.

Therefore, to declare the array you would use the following syntax:

Dim iVar(2,4) as Integer

Whereas you can consider a two-dimensional array to be a rectangle, you can consider a three-dimensional array to be a rectangular block. To declare a three-dimensional array of integers, use

Dim iVar(1,2,1) as Integer


In the array iVar, the value assigned to each element, as depicted in Figure 11.4, is as follows:

iVar(0,0,0) = 5
iVar(0,1,0) = 187
iVar(0,2,0) = 16
iVar(1,0,0) = 12
iVar(1,1,0) = 55
iVar(1,2,0) = 7
iVar(0,0,1) = 34
iVar(0,1,1) = 13
iVar(0,2,1) = 4500
iVar(1,0,1) = 612
iVar(1,1,1) = 9
iVar(1,2,1) = 784

Just as with a one-dimensional array, you can use the To keyword when declaring the subscript range of each dimension in a multidimensional array. Thus, the line

Dim dMyArray(1 To 5, 3 To 8, 3 To 5) As Double

would declare a three-dimensional array of Double values, five columns wide by six rows tall by three planes deep.

You can also use the Redim keyword to resize a multidimensional array. If you use the Preserve keyword, however, only the last dimension of a multidimensional array can be resized, and the number of dimensions can't be changed.

No comments:

Post a Comment