Do Until Loops
This page was last reviewed on Feb 16, 2023.
Dot Net Perls
Do Until. All loops in VB.NET have a similar purpose. They cause a block of statements to repeat a certain number of times. The Do Until loop is similar to the Do While loop.
Notes, syntax. Do Until uses a slightly different syntax than Do While. In this loop, the Until condition causes termination when it evaluates to True.
Do While
This program uses both a Do Until loop and a Do While loop. The Do Until loop has the condition "i = 10". This loop will continue repeating until the variable "i" is equal to ten.
Warning This syntax can easily result in an infinite loop if you are not careful.
And We find that Do Until has all the same problems as While and Do While in this respect.
Module Module1 Sub Main() Dim i As Integer = 0 ' Example Do Until loop. Do Until i = 10 Console.WriteLine("Do Until: {0}", i) i += 1 Loop Console.WriteLine() i = 0 ' Equivalent Do While loop. Do While i < 10 Console.WriteLine("Do While: {0}", i) i += 1 Loop End Sub End Module
Do Until: 0 Do Until: 1 Do Until: 2 Do Until: 3 Do Until: 4 Do Until: 5 Do Until: 6 Do Until: 7 Do Until: 8 Do Until: 9 Do While: 0 Do While: 1 Do While: 2 Do While: 3 Do While: 4 Do While: 5 Do While: 6 Do While: 7 Do While: 8 Do While: 9
Syntax. This syntax may be more readable if the terminating condition for the loop is the most intuitive. It really just depends on what you prefer.
Note The Do While syntax is more expected for developers used to C# or C-like languages.
Info The Do Until syntax could be thought of as a "Do While Not" syntax. It changes a Do While loop to evaluate while False.
Iteration. Iteration variables in the Do Until loop must be incremented with a separate statement. If you have an iteration variable (such as i) it is probably better to use a For-loop.
And If you looping over elements of a collection, it is probably best to use a For-Each loop.
A review. Do Until may provide a clearer syntax for loops in some programs. For developers of languages based on C, though, the syntax may be less intuitive and worth avoiding.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 16, 2023 (edit link).
© 2007-2024 Sam Allen.