Loop, Do While

We have seen sequential and conditional execution of programs, and we will now look at looping, the repetitive execution of instructions. (In a subsequent note, we will cover a fourth flow mechanism called recursion in which a function calls itself).

There are three loop statements in Visual Basic, For, Do while and Do until. This note discusses Do While loops. A general form of a Do While loop is:

Do While <boolean expression>

   body: statements to execute while
   the boolean expression is true

Loop
This inflexible loop program uses a Do While loop:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   txtOut.Clear()
   Dim i As Integer
   i = 2
   Do While i <= 10
      txtOut.AppendText("loop" & " " & CStr(i) & vbCrLf)
      i = i + 2
   Loop
End Sub
The loop repeats as long as the Boolean expression is true. (In this case, that is while the variable i is less than or equal 10). Note that at least one of the statements in the body of the loop must change the value of the variables used in the Boolean expression if the loop is ever to terminate. (The statement i = i + 2 does that in this example).

This generalized Do While program lets the user control the loop:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   Dim intStart As Integer  'initial index value
   Dim intInc As Integer    'index increment
   Dim intEnd As Integer    'index limit
   Dim i As Integer         'index variable
   txtOut.Clear()
   intStart = CInt(txtInitial.Text)
   intInc = CInt(txtIncrement.Text)
   intEnd = CInt(txtLimit.Text)
   i = intStart
   Do While i <= intEnd
      txtOut.AppendText("loop" & "  " & CStr(i) & vbCrLf)
      i = i + intInc
   Loop
End Sub

Note that there is a risk of getting into an infinite loop when experimenting with this program. For example, if you tell it to increment the index by 0, it will never end.

Note that this program is also restricted to positive increments. If it tries to count down, the initial value of the index will be greater than the limit, and the program will not execute the loop even once because the Boolean expression is tested before the loop is executed.

In the above example, the conditional test is done at the start of the loop. A Do While loop may be written with the test at the end. The syntax is:

Do

   body: statements to execute while
   the boolean expression is true

Loop While <boolean expression>
If a Do While statement is written this way, it will always be executed at least one time, before the limit is tested.

Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.