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