Looping
- Last UpdatedJul 05, 2024
- 2 minute read
This is the syntax for several variations of looping.
The do loop is the most complex in that it has multiple forms. The first form is the Do While loop. This loop is a typical while loop in that the condition is checked at the start of the loop and the loop executes until the condition is false. The parentheses around the conditions are optional but aid readability.
Note: This example also shows how to exit the do loop if desired.
Dim Check As Boolean
Dim Counter As System.Int32
Do While (Counter < 20 )
Counter += 1 ' Increment Counter.
If (Counter = 10) Then ' If condition is True,
Check = False ' Set value of flag to False.
Exit Do ' Exit loop.
End If
Loop
To ensure that the loop is run at least once, do the check at the end. This also applies to the Until keyword which is discussed later.
Dim Check As Boolean
Dim Counter As System.Int32
Do
Counter += 1 ' Increment Counter.
If (Counter = 10) Then ' If condition is True,
Check = False ' Set value of flag to False.
Exit Do ' Exit loop.
End If
Loop While (Counter < 20 )
To loop until a particular condition is true, instead of while it is true, use the Until statement as follows:
Dim Check As Boolean
Dim Counter As System.Int32
Do Until (Counter >= 20 )
Counter += 1 ' Increment Counter.
If (Counter = 10) Then ' If condition is True,
Check = False ' Set value of flag to False.
Exit Do ' Exit loop.
End If
Loop
The for loop is another standard looping structure. With the for loop the variables are set forth at the beginning of the loop and the loop auto-increments the variant until it reaches its goal. Most of the time the loop variant is a numeric value, but this works for anything that supports comparison operations and the + operation.
Dim J As System.Int32
For J = 2 To 10 Step 2
Total = Total + J
If (J < 0) Then
Exit For
End If
Next J
Loops can be nested if desired. The following shows an example:
Dim J As System.Int32
For J = 2 To 10 Step 2
Total = Total + J
Dim Check As Boolean = True
Dim Counter As System.Int32
Do Until (Counter >= 20 )
Counter += 1 ' Increment Counter.
If (Counter = 10) Then ' If condition is True,
Check = False ' Set value of flag to False.
Exit Do ' Exit loop.
End If
Loop
If (Check = False) Then
Exit For
End If
Next J