Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

282 Part II Programming Fundamentals


to process the array, I chose a slightly more complex syntax involving the UBound
function for future flexibility. The For loop construction:

For i = 0 To UBound(Temperatures)
determines the upper bound of the array by using the UBound statement. This
technique is more flexible because if the array is expanded or reduced later, the For
loop automatically adjusts itself to the new array size.
To fill the array with temperatures, the event procedure uses an InputBox function,
which displays the current day by using the For loop counter.


  1. Display the form again, and then double-click the Display Temps button (Button2).

  2. Type the following statements in the Button2_Click event procedure:


Dim Result As String
Dim i As Short
Dim Total As Single = 0
Result = "High temperatures for the week:" & 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 / 7, "0.0")
TextBox1.Text = Result
This event procedure uses a For... Next loop to cycle through the elements in the
array, and it adds each element in the array to a string variable named Result, which is
declared at the top of the event procedure. I’ve used several literal strings, constants,
and string concatenation operators (&) to pad and format the string by using carriage
returns (vbCrLf), tab characters (vbTab), and headings. The vbCrLf constant, used
here for the first time, contains the carriage return and line feed characters and is an
efficient way to create new lines. The vbTab constant is also used here for the first time
to put some distance between the day and temperature values in the Result string. At
the end of the event procedure, an average for the temperatures is determined, and
the final string is assigned to the Text property of the text box object, as shown in this
statement:

TextBox1.Text = Result


  1. Click the Save All button on the Standard toolbar to save the project. Specify the
    C:\Vb10sbs\Chap11 folder as the location.
    Now you’ll run the program.


Tip The complete Fixed Array program is located in the C:\Vb10sbs\Chap11\Fixed Array
folder.
Free download pdf