Learning the Visual Basic .NET Language - Loop Structures
(Page 8 of 9 )
Loop structures allow you to repeat a segment of code multiple times. There are three basic types of loops in Visual Basic .NET. You choose the type of loop based on the type of task you need to perform. Your choices are as follows:
- You can loop a set number of times with a For … Next loop.
- You can loop through all the items in a collection of data using a For Each loop.
You can loop until a certain condition is met, using a Do … Loop.
For … Next and For Each loops are ideal for chewing through sets of data that have a known, fixed size. Do … Loop is a more flexible construct that allows you to continue processing until a complex condition is met. Do … Loop is often used with repetitive tasks or calculations that don’t have a set number of iterations.
The For … Next Block The For … Next block is a basic ingredient in many programs. It allows you to repeat a block of code a set number of times, using a built-in counter. To create a For … Next loop, you need to specify a starting value, an ending value, and the amount to increment with each pass. Here’s one example:
Dim i As Integer
For i = 1 To 10 Step 1
' This code executes 10 times.
Debug.Write(i)
Next
In this example, the counter you’re using is a variable named i. The loop begins at 1 and ends at 10. The “Step 1” clause specifies that i will be increased by 1 each time the code passes through the loop. You can omit this part of the code, because 1 is the default increment. Once i reaches 10 the final pass is made through the loop.
If you run this code using a tool like Visual Studio .NET, it will write the following numbers in the Debug window:
1 2 3 4 5 6 7 8 9 10
It often makes sense to set the counter variable based on the number of items you’re processing. For example, you can use a For … Next loop to step through the elements in an array by checking the size of the array before you begin. Here’s the code you would use:
Dim StringArray() As String = {"one", "two", "three"}
Dim i As Integer
For i = 0 To StringArray.GetUpperBound(0)
Debug.Write(StringArray(i) & " ")
Next
This code produces the following output:
one two three
...............................................................................................................................
Scope Changes from Visual Basic 6
In traditional Visual Basic, there were only two types of scope for a variable: form level and procedure level. VB .NET tightens these rules a notch by introducing block scope. Block scope means that any variables created inside a block structure (such as a conditional If… End If or a For… Next or a Do… Loop) are only accessible inside that block of code.
For i = 0 To 10
Dim TempVariable As Integer
' (Do some calculation with TempVariable.)
Next
' You cannot access TempVariable here.
This change won’t affect many programs. It’s really designed to catch a few more accidental errors. If you need to access a variable inside and outside of some type of block structure, just define the variable before the block starts.
.............................................................................................................................
The For Each Block VB .NET also provides a For Each block that allows you to loop through the items in a set of data. With a For Each block, you don’t need to create an explicit counter variable. Instead, you create a variable that represents the type of data you’re looking for. Your code will then loop until you’ve had a chance to process each piece of data in the set.
For Each is particularly useful for traversing the data in collections and arrays. For example, the next code segment loops through the items in an array using For Each. This code is identical to the previous example, but a little simpler.
Dim StringArray() As String = {"one", "two", "three"}
Dim Element As String
For Each Element In StringArray
' This code loops three times, with the Element variable set to
' "one", then "two", and then "three".
Debug.Write(Element & " ")
Next
In this case, the For Each loop is looking for string in the array. Thus, if defines a string variable named Element. If you used code like this, you wouldn’t retrieve any information at all:
Dim StringArray() As String = {"one", "two", "three"}
Dim Element As Integer
For Each Element In StringArray
' This code never executes, because there are
' no integers in this array.
Next
For Each iteration has one key limitation: It’s read-only. For example, if you wanted to loop through an array and change the values in that array at the same time, For Each code wouldn’t work. Instead, you would need to fall back on a For … Next block with a counter.
The Do … Loop Block Finally, Visual Basic supports a Do … Loop structure that tests a specific condition after each pass through the loop. To build your condition, you use the While or Until keyword. These two keywords are opposites. While means “as long as this is true,” and Until means “as long as this is not true.”
Here’s an example that loops ten times. After each pass, the code evaluates whether the counter (i) has exceeded a set value.
Dim i As Integer = 1
Do
i += 1
' This code executes 10 times.
Loop While i < 10
You can also place the condition at the beginning of the loop. In this case, the condition is tested before the loop is started. The following code is equivalent to the previous example, unless the condition you’re testing is False to begin with. In that case, none of the code in the loop will execute.
Dim i As Integer = 1
Do While i < 10
i += 1
' This code executes 10 times.
Loop
On the other hand, if you place the condition at the end of the loop, the code will always be executed at least once.
TIP Sometimes you need to exit a loop in a hurry. To do so, you’ll need to use the corresponding Exit statement. For example, you can jump out of a For … Next or For Each loop using the Exit For statement, and you can escape from a Do … Loop with Exit Do.
Next: Functions and Subroutines >>
More Visual Basic.NET Articles
More By Apress Publishing
|
This article is excerpted from chapter three of the book Beginning ASP.NET in VB.NET: From Novice to Professional, written by Matthew MacDonald (Apress, 2004; ISBN: 1590592786). Check it out at your favorite bookstore today. Buy this book now.
|
|