Visual Basic Do Until Loop

In the previous tutorial we covered the fundamentals of loops covering the Do While Loop.  Visual Basic has three main loop structures and in this second instalment we will look at the Do While’s cousin, the Do Until loop.

To recap, a loop allows will execute a block of code a number of times until a condition is met.  They typically look as follows.

Start loop

     Code

End loop when some condition is met

More specifically, the Do While Loop looks like

Do While Condition = True

     Code

Loop

The Do Until Loop on the other hand looks as follows

Do Until Condition = True

    Code 

Loop

This loop is another favourite instruction of my girlfriend, Do something Until she says otherwise.    Unlike the Do While Loop which exits the loop when an expression becomes true, the Do Until Loop exits when a condition becomes true.

Do Until I say otherwise
     Look after the baby
Loop

A more classic example would be

Dim i as Integer

i = 0

Do Until i = 10

     i = i + 1

     ListBox.Items.Add( i )
Loop

The loop will continue while the condition is negative.  Due to the inherent negative nature of the loop, my girlfriend tends to use this instruction while she is angry.  I prefer the Do While Loop.  It must be a subconscious thing.  It’s certainly one of taste as both loops will perform exactly the same function, they are just expressed slightly different to one another.  A part of me wonders why Microsoft didn’t just plumb for one and not other.  They didn’t though, so here we are.

One point worth noting is that in the above example, the ListBox will have the numbers 1 through to 9 added to it.   Not 10 as you might expect.  Visual Basic will exit the loop when i = 10.

In this tutorial the tutor will demonstrate how to use the loop to add the numbers 1 through to 10 to a Listbox.  He also writes the same routine using both the Do While Loop and converts it into a Do Until Loop.  He even states he prefers the Do While Loop so I’m guessing he has children too….

Anyway, here’s the tutorial.

Enjoy.