Loop, Do Until

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 Until loops. The general form of a Do Until loop is:

Do Until <boolean expression>

   body: statements to execute until
   the boolean expression becomes true

Loop
This inflexible loop program uses a Do Until 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 Until 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 Until 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 Until 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 only works if the increment is positive. If the user enters a negative increment in an attempt to count down, the program terminates without executing the loop because the index will be greater than the limit before the first test at the start of the loop.

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

Do

   body: statements to execute until
   the boolean expression becomes true

Loop Until <boolean expression>
If a Do Until 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.