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 LoopThis 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 SubThe 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.