Visual Basic Do Until Loop

In the previous tutorial we covered the fundamentals of loops covering perhaps the simplest loop to digest, 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 executes while something is true and 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 condition becomes false, 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 > 50

     i = i + 1

     ListBox.Items.Add( i )
Loop

This loop will continue until the integer i is greater than 50.  The Do While Loop would loop while the condition is positive, whereas the Do Until Loop will continue until the condition is positive (which is the same as saying ‘while the condition is negative’).  It seems like a more negative loop to me.  Probably due my girlfriend who 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 the other.  They didn’t though, so here we are.  Only one more loop to go then the fun stuff starts!

The following video tutorial demonstrates how to use this loop in your code