Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

292 Part II Programming Fundamentals


Dim i As Integer
For i = 0 To UBound(RandArray)
RandArray(i) = Int(Rnd() * 1000000)
TextBox1.Text = TextBox1.Text & RandArray(i) & vbCrLf
ProgressBar1.Value = i 'move progress bar
Next i
End Sub
To get random numbers that are integers, I used the Int and Rnd functions together,
as I did in Chapter 2, “Writing Your First Program,” and I multiplied the random
number produced by Rnd by 1,000,000 to get whole numbers that are six digits or
less. Assigning these numbers to the array is facilitated by using a For... Next loop
with an array index that matches the loop counter (i). Filling the array is an extremely
fast operation; the slowdown (and the need for the progress bar) is caused by the
assignment of array elements to the text box object one at a time. This involves
updating a user interface component on the form 500 times, and the process takes a
few seconds to complete. It is instructional, however—the delay provides a way for me
to show off the ProgressBar control. Since the progress bar object has been calibrated
to use the number of array elements as its maximum, assigning the loop counter (i) to
the progress bar’s Value property allows the bar to display exactly how much of the
calculation has been completed.


  1. Click the Sort Array button.


The program follows a similar process to sort RandArray, this time using the Array.
Sort method to reorder the array in ascending order. (The 500 elements are listed from
lowest to highest .) Your screen looks like this:

The code that produced this result is the Button2_Click event procedure, which contains
the following program statements:

'Sort the array using the Array.Sort method and display
Private Sub Button2_Click(ByVal sender As System.Object, _
Free download pdf