Software applications often work with sets of related data, not just isolated data values. Visual Basic includes two primary ways of working with such sets of data: collections (discussed in Chapter 16) and arrays. An array assigns a numeric position to each item included in the set, starting with 0 and ending with one less than the number of items included. An array of five items has elements numbering from 0 to 4.
As an example, imagine that you were developing a zoo simulation application. You might include an array named
animals that includes each animal name in your zoo:
Animal #0: Aardvark
Animal #1: Baboon
Animal #2: Chimpanzee
Animal #3: Donkey
. . . and so on . . .
Visual Basic identifies array elements by a parenthesized number after the array name. For our animals, a simple assignment puts the
String name of each animal in an array element.
animal(0) = "Aardvark" animal(1) = "Baboon" animal(2) = "Chimpanzee" animal(3) = "Donkey"
Using each array element is just as easy.
MsgBox("The first animal is: " & animal(0))
Each element of an array is not so different from a standalone variable. In fact, you could just consider the set of animals in the example code to be distinct variables: a variable named
animal(0), another variable named
animal(1), and so on. But they are better than ordinary variables because you can process them as a set. For instance, you can scan through each element using a
For...Next loop. Consider an
Integer array named
eachItem with elements numbered from ...