Suppose in VB.NET we wish to continue looping until a condition is met. The number of iterations though may be unknown (as of yet).
With Do While, and While, we can loop indefinitely (and stop at a certain point). These loops are ways to continue iterating while one or more conditions are true.
A Do While loop can have one or more conditions in its expression. Here we use 2 conditions. We continue iterating while "i" is positive and "z" is less than or equal to 8.
Module Module1 Sub Main() ' Locals used in Do While loop. Dim i As Integer = 100 Dim z As Integer = 0 ' Loop. Do While i >= 0 And z <= 8 Console.WriteLine("i = {0}, z = {1}", i, z) i = i - 10 z = z + 3 Loop End Sub End Modulei = 100, z = 0 i = 90, z = 3 i = 80, z = 6
With Do we can loop infinitely (or indefinitely). This loop gets a random number on each iteration. If the number is even, it uses "Exit Do" to stop the loop.
Module Module1 Sub Main() Dim random As New Random() ' Enter a loop. Do ' Get random number. Dim number As Integer = random.Next ' Print random number. Console.WriteLine(number) ' Exit loop if we have an even number. If number Mod 2 = 0 Then Exit Do End If Loop End Sub End Module1315809053 1322882256
In VB.NET we can use a Do Until loop to mean "continue until the condition is matched." A Do While loop can be used in the same way.
Module Module1 Sub Main() Dim index As Integer = 0 Dim array() As Integer = New Integer() {10, 20, 30, 40} ' Use "not equals" operator. Do While array(index) <> 30 Console.WriteLine("[WHILE] NOT 30: {0}", array(index)) index += 1 Loop ' Use "do until" loop. index = 0 Do Until array(index) = 30 Console.WriteLine("[UNTIL] NOT 30: {0}", array(index)) index += 1 Loop End Sub End Module[WHILE] NOT 30: 10 [WHILE] NOT 30: 20 [UNTIL] NOT 30: 10 [UNTIL] NOT 30: 20
Next, we can use a "While" loop without the "Do" keyword. While
-loops are useful for cases where we do not know beforehand how many iterations will run.
While
-loop's body are executed repeatedly until that condition evaluates to false.While
-loop.Module Module1 Sub Main() Dim i As Integer = 0 While i < 100 Console.WriteLine(i) i += 10 End While End Sub End Module0 10 20 30 40 50 60 70 80 90
Do While in VB.NET is a loop that will continue until the exit condition is met. This can lead to infinite loops unless you are careful.