16.6. Iteration Statements


In a VB.NET method, you will find many situations in which you want to do the same thing again and again, perhaps slightly changing a value each time you repeat the action. This is called iteration or looping. Typically, you'll iterate (or loop) over a set of items, taking the same action on each. This is the programming equivalent to an assembly line: take a hundred car bodies and put a windshield on each one as it comes by.

VB.NET provides an extensive suite of iteration statements , including Do and For.

16.6.1. The Do Loop

The semantics of a Do loop are "Do this work while a condition is true" or "Do this work until a condition becomes true." You can test the condition either at the top or at the bottom of the loop. If you test at the bottom of the loop, the loop will execute at least once.

The Do loop can even be written with no conditions; in which case, it will execute indefinitely, until it encounters an Exit Do statement.

Do loops come in the following flavors:

 Do While BooleanExpression    statements Loop Do Until BooleanExpression     statements Loop Do     statements Loop while BooleanExpression Do    statements Loop until BooleanExpression Do     statements Loop 

In each case, the BooleanExpression can be any expression that evaluates to a Boolean value of TRue or False.

16.6.1.1. Do While

The first kind of Do loop, Do While, executes only while the BooleanExpression returns TRue, as shown in Example 16-9.

Example 16-9. Using Do While
 Option Strict On Module Module1    Sub Main(  )       Dim counterVariable As Integer = 0       Do While counterVariable < 10          Console.WriteLine("counterVariable: {0}", counterVariable)          counterVariable = counterVariable + 1       Loop ' While counterVariable < 10    End Sub 'Main End Module Output: counterVariable: 0 counterVariable: 1 counterVariable: 2 counterVariable: 3 counterVariable: 4 counterVariable: 5 counterVariable: 6 counterVariable: 7 counterVariable: 8 counterVariable: 9 

16.6.1.2. Do Until

The second version of Do:

  Do Until BooleanExpression     statements Loop 

executes until the BooleanExpression returns TRue.

Be very careful when looping to a specific value. If the value is never reached or is skipped over, your loop can continue without end, causing your program to "hang."


The two constructs are closely related; which one you use will depend on the semantics of the problem you are trying to solve. That is, use the construct that represents how you think about the problem. If you are solving this problem: "keep winding the box until the Jack pops up," then use a Do Until loop. If you are solving this problem: "As long as the music plays, keep dancing," then use a Do While loop, though either construct will work ("keep dancing until the music stops.")

The two variants:

 Do     statements Loop while BooleanExpression Do    statements Loop until BooleanExpression 

are used when you want to ensure that the loop runs at least once, whatever the starting conditions. Thus, although your counterVariable might be initialized to 100, you want to make sure the loop runs once anyway. You'll use the Do... Loop While construct.

16.6.1.3. Breaking out of a Do loop

You can break out of any Do loop with the Exit Do statement. You must break out of the final Do construct:

 Do     statements Loop 

because otherwise it will never terminate. You typically use this construct when you do not know in advance what condition will cause the loop to terminate (e.g., the termination may be in response to user action).

16.6.2. While Loops

As further proof that there are many ways to accomplish the same thing, VB.NET also offers a While loop construct that is closely related to the Do...While loops. The syntax is:

 while BooleanExpression   statements End While 

16.6.3. The For loop

When you need to iterate over a loop a specified number of times, you can use a For loop with a counter variable. The syntax of the For loop is:

 For variable= expressionto expression [ step expression]    statements Next [ variable-list ] 

The simplest and most common form of this statement creates a loop variable to count through the iterations of the loop. For example, you might create an integer variable loopCounter that you will use to step through a loop ten times, as shown in Example 16-10.

Example 16-10. For loop
 Option Strict On Module Module1    Sub Main(  )       Dim loopCounter As Integer       For loopCounter = 0 To 9          Console.WriteLine("loopCounter: {0}", loopCounter)       Next    End Sub 'Main End Module Output: loopCounter: 0 loopCounter: 1 loopCounter: 2 loopCounter: 3 loopCounter: 4 loopCounter: 5 loopCounter: 6 loopCounter: 7 loopCounter: 8 loopCounter: 9 

The variable (loopCounter) can be of any numeric type. For example, you might initialize a Single rather than an Integer, and step up through the loop from 0.5 to 9.

You can also modify multiple variables on each Next statement. This allows you to nest one For loop within another. You might use an outer and an inner loop to iterate through the contents of collections. A simple example of this technique is shown in Example 16-11.

Example 16-11. Multiple updates with one Next statement
 Option Strict On Module Module1    Sub Main(  )       Dim outer As Integer       Dim inner As Integer       For outer = 3 To 6          For inner = 10 To 12             Console.WriteLine("{0} * {1} = {2}", _                 outer, inner, outer * inner)       Next   inner, outer    End Sub 'Main End Module 3 * 10 = 30 3 * 11 = 33 3 * 12 = 36 4 * 10 = 40 4 * 11 = 44 4 * 12 = 48 5 * 10 = 50 5 * 11 = 55 5 * 12 = 60 6 * 10 = 60 6 * 11 = 66 6 * 12 = 72 

As an alternative to updating both counters in the same Next statement, you can provide each nested For loop with its own Next statement:

 For outer = 3 To 6     For inner = 10 To 12        Console.WriteLine("{0} * {1} = {2}", _            outer, inner, outer * inner)     Next inner  Next outer 

When you update a single value in a Next statement, you are free to leave off the variable you are updating. Thus, the previous code is identical to this code:

 For outer = 3 To 6     For inner = 10 To 12        Console.WriteLine("{0} * {1} = {2}", _            outer, inner, outer * inner)     Next  Next 

Using the variable name in Next statements is generally preferred by VB.NET programmers because it makes for code that is easier to understand and maintain.




Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net