Visual Basic 2005 Guide


An array is a data structure that allows you to store as many items as you need to using a single variable name. So far you have had to use a different variable name to store each different piece of information. For example,

Dim intFirstNumber As Integer
Dim intSecondNumber As Integer
Dim intThirdNumber As Integer

With an array we could store the numbers as follows.

Dim intNumbers(2) As Integer

The first number would be stored as intNumbers(0), the second at intNumbers(1) and so on. The number in brackets is called the subscript.

Example Program

This program needs a form with a multiline text box called txtOutput. Double click on the form and write this code in the form's load event handler.

Dim name(4) As String
Dim score(4) As Integer
Dim intCounter As Integer
'Read in the names and scores
For intCounter = 0 To 4
   name(intCounter) = InputBox("Enter name of person " & intCounter)
   score(intCounter) = InputBox("Enter score for person " & intCounter)
'calculate the total and mean
Dim intTotal As Integer, sglMean As Single
For intCounter = 0 To 4
   intTotal = intTotal + score(intCounter)
sglMean = intTotal / 5
'output scores above the mean
For intCounter = 0 To 4
   If score(intCounter) > sglMean Then
      txtOutput.Text = txtOutput.Text & name(intCounter) & " " & score(intCounter) & vbNewLine
   End If

The lines of code in bold are comments. Comments are used by programmers to explain the code for themselves and for other users. They are ignored by Visual Basic when the code is executed. To type a comment you start the line with an apostrophe.

Programming Tasks

  1. Create a program that generates an array of 100 random numbers. Output these numbers to a text box.
  2. Adapt the program that you wrote to tell the user how many of the numbers fall in the ranges 0 - 10, 11 - 20, 21, 30 and so on. The more inventive you are, the shorter this program could be. This is a case where the shortest working program wins.