Statements in a Visual Basic program are normally executed in the physical order of their appearance unless altered by a decision structure such as an If or Select statement. Even in these cases the statements are executed in a top-to-bottom sequence.
There are certain processing situations, however, that require a set of statements to be executed repeatedly -- to iterate over and over again until a certain condition is met. You might, for instance, need to look through the items in an array, one at a time, until you find a matching value. The code to effect this seach needs to execute again and again, each time indexing to the next element in the array.
The For...Next Loop
Visual Basic provides this ability to iterate a set of statements with the For...Next statement whose general format is shown below.
A For...Next loop establishes a counter to keep track of iterations through the enclosed statements. It is given a start value and an end value -- integer values -- to control the number of times the statements are executed, with the counter incremented by 1 each time through the loop.
The following code, for example, executes the statements in the For...Next loop 10 times.
Dim i As Integer For i = 1 To 10 ...statements Next
Variable i is defined as the counter. (This choice of counter names owes an historical debt to Fortran programming.) The counter is initialized to 1 when the loop is first entered. After the statements are executed the first time and the Next statement is encountered, program control returns to the matching For statement. The counter is incremented by 1 and a test is made to see if the counter has yet reached the end value 10. If not, the statements are executed a second time, and control again returns to the For statement where the counter is incremented again and is tested against the end value. This processing continues until finally the counter exceeds the end value and the loop comes to an end. Then, program control "skips over" the loop and continues in sequence with the statement following Next.
In the above example, start value and end value are given literal integer values. More likely, start value, and especially end value, are assigned through variables set elsewhere in the script.
The following script is a simple illustration of a For...Next loop. The user enters an integer value that is used as the ending value for the loop. Beginning with 1, the loop displays the sequence of integers to the ending value.
Sub Make_Numbers (Src As Object, Args As EventArgs) If IsNumeric(EndValue.Text) Then Dim i As Integer For i = 1 To EndValue.Text Numbers.Text &= i & " " Next End If End Sub <asp:TextBox id="EndValue" Size="1" MaxLength="2" runat="server"/> <asp:Button Text="Make Numbers" OnClick="Make_Numbers" runat="server"/> <asp:Label id="Numbers" EnableViewState="False" runat="server"/>
Since loop counter values must be numeric, a test is made at the beginning of the subprogram for a numeric value in the textbox. Each time through the loop, increasing values of counter i are concatenated to the previously displayed string of values, separated by a blank space.
Iterating Arrays
The For...Next loop provides an ideal mechanism for iterating the elements in an array. The counter can be set up to increment through the array's indexes, pointing in sequence to each element from the first through the last. Returning to a previous example, the following array contains the first five letters of the Greek alphabet. A loop is set up to display, in turn, each of these five letters.
Sub Get_Greek (Src As Object, Args As EventArgs) Dim Letters() As String = {"alpha","beta","gamma","delta","epsilon"} Dim i As Integer For i = 0 To Letters.Length - 1 GreekOut.Text &= Letters(i) & " " Next End Sub <asp:Button Text="Get Greek" OnClick="Get_Greek" runat="server"/> <asp:Label id="GreekOut" EnableViewState="False" runat="server"/>
Since the loop needs to iterate the five elements of the array, the counter is set to begin at 0 and to end at 4, thereby taking on the five index values for the array. The display of Letters(i), then, displays each of the five values.
Array Lengths
The ending value of the above loop is not set to literal integer 4. It could be set to this value since it is known in advance that there are five elements in the array. A more generally useful way of setting an ending value for an array loop is to determine programmatically how many elements there are, and subtract 1. The size of an array is given by its Length property. Since the length of an array is counted from 1 (Letters.Length = 5 in the above example), the ending value of the loop counter is one less than its length.
Table Lookup
A popular use of arrays and loops is to perform a table lookup -- to search an array for a matching value. This application normally involves two arrays, called corresponding arrays, where the values in one array have corresponding values in the second array. Consider the case where you wish to look up the Greek letter that corresponds to an English letter. This application is implemented below. Enter an English letter (upper- or lower-case) in the textbox and its Greek equivalent is displayed when the button is clicked. To save typing only the first five letters are used.
Sub Get_Match (Src As Object, Args As EventArgs) Dim Greek() As String = {"alpha","beta","gamma","delta","epsilon"} Dim English() As String = {"a","b","c","d","e"} Dim i As Integer For i = 0 To English.Length - 1 If English(i) = LCase(EnglishLetter.Text) Then GreekLetter.Text = Greek(i) Exit For End If Next End Sub <asp:TextBox id="EnglishLetter" Size="1" MaxLength="1" runat="server"/> <asp:Button Text="Get Greek" OnClick="Get_Match" runat="server"/> <asp:Label id="GreekLetter" EnableViewState="False" runat="server"/>
Arrays Greek and English have corresponding values in their elements; that is, each value in one array has a matching value in the same element of other array. The For...Next loop is set up to iterate all elements of the English array, testing for a match to the entered letter (converted to lower case to match array values). If no match is found at a particular element, the counter increments to the next element. When a match is made, the value of the counter points to an element of the Greek array containing the corresponding letter -- the value in English(i) corresponds to the value in Greek(i). So, Greek(i) is displayed. If no match to the entered letter is found, the loop ends without display.
It is not necessary to continue iterating the English array once a match is found to the entered letter. Therefore, the Exit For statement is used to immediately exit the For...Next loop after a Greek letter is displayed.
Table Lookup in Multidimensional Arrays
The above corresponding arrays can be implemented as a single multidimensional array with two columns. This code is shown below.
Sub Get_Match (Src As Object, Args As EventArgs) Dim Letters() As String = {{"alpha","a"},{"beta","b"},{"gamma","c"},{"delta","d"},{"epsilon","e"}} Dim i As Integer For i = 0 To Letters.Length - 1 If Letters(i,0) = LCase(EnglishLetter.Text) Then GreekLetter.Text = Letters(i,1) Exit For End If Next End Sub
Just keep in mind that English letters are in the first column (0) of the array and Greek letters are in the second column (1). The counter iterates through the rows, looking in the first column (i,0) for a match to the entered value. When found, the corresponding Greek letter is in the second column of this same row (i,1).
Whether you choose to use corresponding arrays or corresponding columns to set up and perform look-ups is a matter of personal choice.
Setting the Counter Increment
The For...Next loop increments its counter from a beginning value to an ending value by adding 1 to the counter on each iteration. You can use other increment values and you can reverse the counter.
By adding Step n to the statement you can establish the amount by which the counter is incremented (the default is Step 1). For example, the following loop displays all odd numbers between 1 and 99 by incrementing the loop counter by 2 each time.
Sub Show_Odds (Src As Object, Args As EventArgs) Dimension i As Integer For i = 1 To 99 Step 2 OddNumbers.Text &= i & " " Next End Sub <asp:Button Text="Odd Numbers" OnClick="Show_Odds" runat="server"/> <asp:Label id="OddNumbers" EnableViewState="False" runat="server"/>
You can also decrement, rather than increment, the counter. The following loop displays all odd numbers between 99 and 1 in reverse order by Step -2.
Sub Show_Reverse_Odds (Src As Object, Args As EventArgs) Dimension i As Integer For i = 99 To 1 Step -2 ReverseOddNumbers.Text &= i & " " Next End Sub <asp:Button Text="Reverse Odds" OnClick="Show_Reverse_Odds" runat="server"/> <asp:Label id="ReverseOddNumbers" EnableViewState="False" runat="server"/>