Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

274 Part II Programming Fundamentals


Arrays can help you track a small set of values in ways that are impractical using traditional
variables. For example, imagine creating a nine-inning baseball scoreboard in a program.
To save and recall the scores for each inning of the game, you might be tempted to create
two groups of 9 variables (a total of 18 variables) in the program. You’d probably name them
something like Inning1HomeTeam, Inning1VisitingTeam, and so on, to keep them straight.
Working with these variables individually would take considerable time and space in your
program. Fortunately, with Visual Basic you can organize groups of similar variables into
an array that has one common name and an easy-to-use index. For example, you can create
a two-dimensional array (two units high by nine units wide) named Scoreboard to contain the
scores for the baseball game. Let’s see how this works.

Creating an Array


You create, or declare, arrays in program code just as you declare simple variables. As usual,
the place in which you declare the array determines where it can be used, or its scope,
as follows:

n If you declare an array locally in a procedure, you can use it only in that procedure.
n If you declare an array at the top of a form, you can use it throughout the form.
n If you declare an array publicly in a module, you can use it anywhere in the project.
When you declare an array, you typically include the information shown in Table 11-1 in your
declaration statement.

TABLE 11-1 Syntax Elements for an Array Declaration
Syntax Elements
in Array Declaration Description
Array name The name you’ll use to represent your array in the program. In general,
array names follow the same rules as variable names. (See Chapter 5,
“Visual Basic Variables and Formulas, and the .NET Framework,” for
more information about variables .)
Data type The type of data you’ll store in the array. In most cases, all the
variables in an array are the same type. You can specify one of the
fundamental data types, or if you’re not yet sure which type of data
will be stored in the array or whether you’ll store more than one type,
you can specify the Object type.
Number of dimensions The number of dimensions that your array will contain. Most arrays are
one-dimensional (a list of values) or two-dimensional (a table of values),
but you can specify additional dimensions if you’re working with a
complex mathematical model, such as a three-dimensional shape. The
number of dimensions in an array is sometimes called the array’s rank.
Number of elements The number of elements that your array will contain. The elements in
your array correspond directly to the array index. The first array index
is always 0 (zero).
Free download pdf