Previous section   Next section

3.8 Iteration (Looping) Statements

There are many situations in which 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 For Each. You can also create a loop by using a statement called Goto. This chapter considers the use of Goto, Do, and For. However, you'll have to wait until Chapter 3 to learn more about For Each.

3.8.1 Creating Loops with Goto

Goto is the most primitive kind of unconditional branching statement, and it is not much used in modern programming. Its most common usage was to create looping statements, and 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 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 3-14.

Example 3-14. 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.

3.8.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.

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 follows. Note that in each case, the BooleanExpression 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 3-15 shows a Do While loop, which in this case does no more than increment a counterVariable from 0 to 9, printing a statement to that effect to the console for each iteration of the loop.

Example 3-15. 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 3-16 modifies Example 3-15 to use Do Until.

Example 3-16. 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 3-16 is identical to that of Example 3-15.

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:

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 3-17.

Example 3-17. 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

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.

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.

3.8.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 3-18, you can basically mimic the Do Loop...While construct demonstrated in Example 3-17.

Example 3-18. 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 3-17, you would loop indefinitely if the If statement did not set up a condition and provide an exit via Exit Do. However, as written, Example 3-19 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.

3.8.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 3-19. Note that the Next keyword is used to mark the end of the For loop.

Example 3-19. 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 3-20.

Example 3-20. 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 1 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 3-21.

Example 3-21. 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

3.8.5 Controlling a For Loop Using Next

You can specify which counter variable the Next statement updates. Thus, rather than writing Next in the previous example, you could have written:

Next loopCounter

One place where you might want to name the variable being incremented is with a nested loop. For example, in Example 3-22 you create an outer loop to count through the values 3 to 6, and an inner loop to count the values 10 to 12.

Example 3-22. Using Next
Option Strict On
Imports System

Module Module1
    Sub Main( )
        Dim inner As Integer
        Dim outer As Integer
        For outer = 3 To 6
            For inner = 10 To 12
                Console.WriteLine("{0} * {1} = {2}", _
                    outer, inner, outer * inner)
            Next inner
        Next outer
    End Sub
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

Notice that the inner loop runs through each value for each value in the outer loop (that is, 10-12 is repeated for each of 3, 4, 5, and 6).

Once again, you are free to leave off the name of the variable you are incrementing because Visual Basic .NET can keep track of the inner and outer loop statements for you. Thus, you can rewrite the loop as:

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

On the other hand, you can combine the two Next statements into one, in which case you do need the variable name:

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

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.


  Previous section   Next section
Top