Thursday, April 3, 2008

Arrays

We learned that we can use arrays as containers to hold several variables of the same type. We also learned about why we might want to use such a structure, for example, sorting 10000 names from within a file.

There are a few ways to declare an array:

  • Dim arr( size ) As Type

  • Dim arr( ) As Type = {item1, item2, ...., itemN}

  • Dim arr( ) As Type
    ...
    ...
    Redim arr( newSize )

In each of the examples above, we have the array name and the type (String, Integer, Double etc) in the declaration statement. In the first example, we indicate the size of the array with an Integer value. This will give us an array with size + 1 cells. This is because we will have subscripts/indexes/cells numbered from 0 to Size.

In the last two examples, the size is not specified in the parentheses. In the second example, the size is figured out by the compiler by looking at the number of items in the list being assigned to each cell. In the third example, the size is set sometime later using a Redim statement.

The Redim statement allows us to reset the size of the array as the program runs. It can be useful for things like taking items in from a file, where the total number of items is unknown, or expanding the array when we need to add more items to it. If we have something in the array before we call Redim, the previous items will be lost. We can save them, however, using the Preserve command:

Redim Preserve arr( newSize )

If the new size is smaller than the original size, all items after the new upperbound will be lost.

We can find the upperbound of an array at anytime with the following code:

arrayname.GetUpperBound(0)

Where arrayname is replaced by the name of your array.

Real Examples
Dim names( 10 ) As String
Dim names2( ) As String = {"Allen", "Stacy", "Simon"}


The result of these declaration statements create two arrays, names() which is of size 11 and names2() size 3. The contents of name2() look like this:
 
0 1 2
+---------+---------+---------+
| "Allen" | "Stacy" | "Simon" |
+---------+---------+---------+


Now if we want to extend names2() we can use the Redim statement:

Redim Preserve names2( 4 )
names2( 3 ) = "Max"

The contents of the array will now be:
 
0 1 2 3 4
+---------+---------+---------+--------+--------+
| "Allen" | "Stacy" | "Simon" | "Max" | |
+---------+---------+---------+--------+--------+


Notice that we used the command Preserve so that we would not loose the previous contents of our array.

No comments: