Saturday, December 26, 2009

Using Loops to Traverse an Array

You can use the For...Next loop that you learned about in Chapter 10, "Working with Loops," to move through, or traverse, an array. This can be useful when you want to change or report values in an array.

Listing 3.12 is an example of using a For...Next loop to traverse an array. The listing is the event procedure for a button click, in which an array of 20 elements is created. A For...Next loop is used twice--first to assign values to every element in the array, and then to find the value assigned to every element and make a string that reports the value of that element

LISTING 3.12 LIST03.TXT--Using For...Next Loops to Traverse an Array

01 Private Sub cmdTraverse_Click()
02 Dim i%
03 Dim iMyArray%(19) As Integer
04 Dim BeginMsg$
05 Dim MidMsg$
06 Dim LoopMsg$
07 Dim FullMsg$
08
09 `Assign a value to each element in the array
10 `by using a loop to traverse to each element
11 `in the array.
12 For i% = 0 To 19
13 `Make the value of the element to be
14 `twice the value of i%
15 iMyArray%(i%) = i% * 2
16 Next i%
17
18 `Create the BeginMsg$ string
19 BeginMsg$ = "The element is: "
20 MidMsg$ = ", The value is: "
21 `Go through the array again and make
22 `a string to display
23 For i% = 0 To 19
24 LoopMsg$ = LoopMsg$ & BeginMsg$ & CStr(i%)
25 LoopMsg$ = LoopMsg$ & MidMsg$ & iMyArray(i%)
26
27 `Concatenate the loop message to the
28 `full message. Also add a line break
29 FullMsg$ = FullMsg$ & LoopMsg$ & vbCrLf
30
31 `Clean out the loop message so that
32 `new value next time through the loop
33 LoopMsg$ = ""
34 Next i%
35
36 txtTraverse.Text = FullMsg$
37 End Sub

The code in Listing 3.12 is simple. Remember that a For...Next loop increments a counting variable as it loops. You assign this counting variable to the element position of the array. Then, set the lower bound of the array (the lowest element number) to the start point of the loop and set the upper bound of the array (the highest element number) to the end point of the loop. When you run the loop, the counting variable will always be at an element of the array.

No comments:

Post a Comment