Section 6.3. Iteration (Looping) Statements

   

6.3 Iteration (Looping) Statements

In many situations you will 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. On an assembly line, you might take a hundred car bodies and put a windshield on each one as it comes by. In an iterative program, you might work your way through a collection of text boxes on a form, retrieving the value from each in turn and using those values to update a database.

VB.NET provides an extensive suite of iteration statements, including Do , For , and Foreach . You can also create a loop by using a statement called Goto . The remainder of this chapter considers the use of Goto , Do , and For . However, you'll have to wait until Chapter 14 to learn more about Foreach .

6.3.1 Creating Loops with Goto

The Goto statement was used previously as an unconditional branch in a switch statement. Its more common usage, however, is to create a loop. In fact, the Goto statement is the seed from which all other looping statements have been germinated. Unfortunately, it is a semolina seed, producer of spaghetti code and endless confusion.

Programs that use Goto statements outside of switch blocks jump around a great deal. Goto can cause your method to loop back and forth in ways that are difficult to follow.

If you were to try to draw the flow of control in a program that makes extensive use of Goto statements, the resulting morass of intersecting and overlapping lines might look like a plate of spaghetti ”hence the term "spaghetti code." Spaghetti code is a contemptuous epithet; no one wants to write spaghetti code.

Most experienced programmers properly shun the Goto statement, but in the interest of completeness, here's how you use it:

  1. Create a label.

  2. Goto that label.

The label is an identifier followed by a colon . You place the label in your code, and then you use the Goto keyword to jump to that label. The Goto command is typically tied to an If statement, as illustrated in Example 6-9.

Example 6-9. Using Goto
 Option Strict On Imports System Module Module1    Sub Main( )       Dim counterVariable As Integer = 0 repeat:  ' the label       Console.WriteLine("counterVariable: {0}", counterVariable)       ' increment the counter       counterVariable += 1       If counterVariable < 10 Then          GoTo repeat ' the dastardly deed       End If    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 

This code is not terribly complex; you've used only a single Goto statement. However, with multiple such statements and labels scattered through your code, tracing the flow of execution becomes very difficult.

It was the phenomenon of spaghetti code that led to the creation of alternatives, such as the Do loop.

6.3.2 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. Every Do loop is bounded by the Loop keyword, which marks the end of the methods to be executed within the loop.

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 a number of varieties, some of which require additional keywords such as While and Until . The syntax for these various Do loops follow. Note that in each case, the Boolean-expression can be any expression that evaluates to a Boolean value of true or false.

  Do While   Boolean-expression   statements   Loop   Do Until   Boolean-expression   statements   Loop   Do   statements   Loop   While   Boolean-expression   Do   statements   Loop   Until   Boolean-expression   Do   statements   Loop  

In the first type of Do loop, Do While , the statements in the loop execute only while the Boolean-expression returns true. Example 6-10 shows a Do While loop, which in this case does no more than increment a counterVariable from 0 to 10, printing a statement to that effect to the console for each iteration of the loop.

Example 6-10. Using Do While
 Option Strict On Imports System 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 

The second version of Do, Do Until , executes until the boolean-expression returns true, using the following syntax:

 Do Until   Boolean-expression     statements   Loop 

Example 6-11 modifies Example 6-10 to use Do Until .

Example 6-11. Using Do Until
 Option Strict On Imports System Module Module1    Sub Main( )       Dim counterVariable As Integer = 0       Do Until counterVariable = 10          Console.WriteLine("counterVariable: {0}", counterVariable)          counterVariable = counterVariable + 1       Loop ' Until counterVariable = 10    End Sub 'Main  End Module 

The output from Example 6-11 is identical to that of Example 6-10.

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

Do While and Do Until are closely related ; which 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.

In order to make sure a Do While or Do Until loop runs at least once, you can test the condition at the end of the loop. The following are the syntax lines to test the condition at the end, for Do While and Do Until , respectively. To distinguish them from the other variants, we'll call them Do Loop While and Do Loop Until .

 Do   statements   Loop While   boolean-expression   Do   statements   Loop Until   boolean-expression   

If your counterVariable were initialized to 100, but you wanted to make sure the loop ran once anyway, you might use the Do Loop While construct, as shown in Example 6-12.

Example 6-12. Do Loop While
 Option Strict On Imports System Module Module1    Sub Main( )       Dim counterVariable As Integer = 100       Do          Console.WriteLine("counterVariable: {0}", counterVariable)          counterVariable = counterVariable + 1       Loop While counterVariable < 10    End Sub 'Main  End Module 
  Output  : counterVariable: 100 

The final Do loop construct is a loop that never ends because there is no condition to satisfy :

 Do   statements   Loop 

The only way to end this construct is to deliberately break out of the loop using the Exit Do statement, described in the next section.

6.3.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 can be in response to user action).

By using Exit Do within an If statement, as shown in Example 6-13, you can basically mimic the Do Loop While construct demonstrated in Example 6-12.

Example 6-13. Using Exit Do
 Option Strict On Imports System Module Module1    Sub Main( )       Dim counterVariable As Integer = 0       Do          Console.WriteLine("counterVariable: {0}", counterVariable)          counterVariable = counterVariable + 1          ' test whether we've counted to 9, if so, exit the loop          If counterVariable > 9 Then             Exit Do          End If       Loop    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 

In Example 6-13, you would loop indefinitely if the If loop did not set up a condition and provide an exit via Exit Do . However, as written, Example 6-13 exits the loop when counterVariable becomes greater than 9. You typically would use either the Do While or Do Loop While construct to accomplish this, but there are many ways to accomplish the same thing in VB.NET. In fact, VB.NET offers yet another alternative, the While loop, as described in the sidebar.

While Loops

VB.NET offers a While loop construct that is closely related to the Do While loop, albeit less popular. The syntax is:

 While   Boolean-expression     statements   End While 

The logic of this is identical to the basic Do While loop, as demonstrated by the following code:

 Option Strict On Imports System Module Module1        Sub Main( )       Dim counterVariable As Integer = 0              While counterVariable < 10          Console.WriteLine("counterVariable: {0}",           counterVariable) counterVariable =           counterVariable + 1       End While        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 

Because the While loop was deprecated in VB6, and because its logic is identical to the more common Do While loop, many VB.NET programmers eschew the While loop construct. It is included here for completeness.

6.3.4 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   =   expression   To   expression  [  Step   expression  ]  statements   Next  [  variable-list  ] 

The simplest and most common use of the For statement is to create a variable to count through the iterations of the loop. For example, you might create an integer variable loopCounter that you'll use to step through a loop ten times, as shown in Example 6-14. Note that the Next keyword is used to mark the end of the For loop.

Example 6-14. Using a For loop
 Option Strict On Imports System 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, as shown in Example 6-15.

Example 6-15. Loop with a Single counter
 Option Strict On Imports System Module Module1    Sub Main( )       Dim loopCounter As Single  For loopCounter = 0.5 To 9  Console.WriteLine("loopCounter: {0}", loopCounter)       Next    End Sub 'Main  End Module 
  Output  : loopCounter: 0.5 loopCounter: 1.5 loopCounter: 2.5 loopCounter: 3.5 loopCounter: 4.5 loopCounter: 5.5 loopCounter: 6.5 loopCounter: 7.5 loopCounter: 8.5 

The loop steps up by one on each iteration because that is the default step value. The next step would be 9.5, which would be above the upper limit (9) you've set. Thus, the loop ends at loopCounter 8.5.

You can override the default step value of 1 by using the keyword Step . For example, you can modify the step counter in the previous example to .5, as shown in Example 6-16.

Example 6-16. Adjusting the step counter
 Option Strict On Imports System Module Module1    Sub Main( )       Dim loopCounter As Single  For loopCounter = 0.5 To 9 Step 0.5  Console.WriteLine("loopCounter: {0}", loopCounter)       Next    End Sub 'Main  End Module 
  Output  : loopCounter: 0.5 loopCounter: 1 loopCounter: 1.5 loopCounter: 2 loopCounter: 2.5 loopCounter: 3 loopCounter: 3.5 loopCounter: 4 loopCounter: 4.5 loopCounter: 5 loopCounter: 5.5 loopCounter: 6 loopCounter: 6.5 loopCounter: 7 loopCounter: 7.5 loopCounter: 8 loopCounter: 8.5 loopCounter: 9 

6.3.5 Controlling a For Loop Using Next

Finally, you can modify multiple variables on each Next statement. This allows you to nest one For loop within another. You might, for example, use an outer and an inner loop to iterate through the contents of collections, as described in Chapter 15. A simple example of this technique is shown in Example 6-17.

Example 6-17. Multiple updates with one Next statement
 Option Strict On Imports System 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 
  Output  : 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 the following code:

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

In both cases, the output will be identical to that of Example 6-17.

VB.NET programmers generally prefer using individual Next statements rather than combining Next statements on one line because it makes for code that is easier to understand and to maintain.

   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

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