Arrays

This note introduces the idea of an array and defines some relevant terms. Other notes give examples of the use of arrays in programs.

As we have seen, variables are used to store data in memory. Each variable has a name and a data type, and memory to hold its value is set aside when it is declared. Variables also have global or local scope.

You can think of an array as a set of variables. Like a variable, an array has a name and a data type, memory is set aside for it when it is declared, and its scope is either global or local.

For example, in a card-game program, you might use an array called suit to hold the names of the suits:

You would create the array by declaring it with a Dim statement, as follows:

dim suit(3) as string
The Dim statement for an array is a variation on the Dim statement for a variable. This statement sets aside four memory locations, each of which holds one string. The array is named suit and each element is referred to by the name of the variable followed by a subscript in parenthesis. For example, the second element in the array has the value "spade" and it is referred to as suit(1). (Note that the subscript of the first element is 0)

You assign values to array elements in the same ways as you assign them to variables or properties. For example, the assignment statement:

suit(3) = "Club"
Would set the value of the fourth element of the array to "Club".

Similarly, we access data stored in arrays the same way we access data stored in variables. For example, the statement:

lblOut.text = suit(3)
Would display Club on the label called lblOut.

The syntax of the Dim statement for arrays is:

Dim <array name> (<greatest subscript>) as <data type>

Where the <greatest subscript> is a numeric expressions. The data types available for arrays are the same as those for variables.

When referencing an element of an array, we use the following syntax:

<array name>  (<subscript>)

Where the subscript is an integer expression.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.