Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 11 Using Arrays to Manage Numeric and String Data 285



  1. Add the following variable declaration just below the Temperatures array declaration:


Dim Days As Integer
The integer variable Days will be used to receive input from the user and to dimension
the dynamic array at run time.


  1. Scroll down in the Code Editor to display the Button1_Click event procedure,
    and modify the code so that it looks like the following. (The changed or added
    elements are shaded .)


Dim Prompt, Title As String
Dim i As Short
Prompt = "Enter the day's high temperature."
Days = InputBox("How many days?", "Create Array")
If Days > 0 Then ReDim Temperatures(Days - 1)
For i = 0 To UBound(Temperatures)
Title = "Day " & (i + 1)
Temperatures(i) = InputBox(Prompt, Title)
Next
The fourth and fifth lines prompt the user for the number of temperatures he or she
wants to save, and then the user’s input is used to dimension a dynamic array. The
If... Then decision structure is used to verify that the number of days is greater
than zero. (Dimensioning an array with a number less than zero or equal to zero
generates an error .) Because index 0 of the array is used to store the temperature for the
first day, the Days variable is decremented by 1 when dimensioning the array. The Days
variable isn’t needed to determine the upper bound of the For... Next loop—as in the
previous example, the UBound function is used instead.


  1. Scroll down in the Code Editor to display the Button2_Click event procedure. Modify
    the code so that it looks like the following routine. (The changed elements are shaded .)


Dim Result As String
Dim i As Short
Dim Total As Single = 0
Result = "High temperatures:" & vbCrLf & vbCrLf
For i = 0 To UBound(Temperatures)
Result = Result & "Day " & (i + 1) & vbTab & _
Temperatures(i) & vbCrLf
Total = Total + Temperatures(i)
Next
Result = Result & vbCrLf & _
"Average temperature: " & Format(Total / Days, "0.0")
TextBox1.Text = Result
The Days variable replaces the number 7 in the average temperature calculation at the
bottom of the event procedure. I also edited the “High temperatures” heading that will
be displayed in the text box.


  1. Display the form.

  2. Change the Text property of Form1 to “Dynamic Array .”

Free download pdf