Multidimensional Arrays VB Help

One-dimensional arrays, such as those presented so far, are good for storing long sequences of one-dimensional data (such as names, and temperatures). But how would you store a list of cities and their average temperatures in an array? Or names and scores, years and profits, or data with more than two dimensions, such as products, prices, and units in stock? In some situations you will want to store sequences of multidimensional data. You can use two one-dimensional arrays or one two dimensional array. Figure 3.3 shows two one-dimensional arrays, one of them with city names, the other with temperatures. The name of the.third city would be City(2) and its temperature would be Temperature(2)).



You can store the same data more conveniently in a two-dimensional array. A . two-dimensional array has two indices. The first identifies the row (the order of the city in the array), and the second identifies the column (city or temperature). To access the name and temperature of the third city in the two-dimensional array, use the following indices:

Tenperatures(2, 0)  is the third city name.
Temperatures(2. 1) is the third city’s average temperature

The-benefit of using multidimensional arrays is that they’re conceptually easier to manage. Suppose you’re writing a game and you want to track the positions of certain pieces on a board. Each square on the board is identified by two numbers, its horizontal and vertical coordinates. The obvious structure for tracking the board’s squares is a two-dimensional array, in which the first index corresponds to the row number and the second index corresponds to the column number. The array could be declared as follows:

Dim Board(10, 10) As Integer

When a piece is moved from the square on the first row and first column to the square on the third row and fifth column, you assign the value 0 to the element that corresponds to the initial position:

Board(1. 1) = 0

and you assign 1 to the square to which it was moved, to indicate the new state of the board:

Board(3, 5) = 1

To find out if a piece is on the upper-left square, you’d use the following statement:

If Board(1, 1) = 1 Then
(piece found)

{empty square}
End If

Notice that this array is not zero-based. It just makes sense to waste the first element to·.code the application in a more familiar way. Board games don’t have zero-numbered rows or columns.

This notation can be extended to more than two dimensions. The following statement creates an array with 1000elements (10 x 10 x10):

Dim Matrix(9, 9, 9)

You can think of a three-dimensional array as a cube made up of overlaid two dimensional arrays, such as the one shown in Figure 3.4.




Posted on November 4, 2015 in Visual Basic: The Language

Share the Story

Back to Top
Share This