VB.NET Do While

Do keyword

A Do While loop uses a special syntax form. How can we use this loop in a VB.NET program? This syntax form provides a way to continue iterating while one or more conditions are true. We examine the Do While construct in this language.

Example

A Do While loop can have one or more conditions in its expression. Here, we use two conditions. We continue iterating while the variable "i" is positive, and while "z" is less than 20.

Then:In each iteration, we change the values of these variables: "i" is decremented by 10 and "z" is incremented by 3.

VB.NET program that uses Do While loop

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 <= 20
	    Console.WriteLine("i = {0}, z = {1}", i, z)
	    i = i - 10
	    z = z + 3
	Loop
    End Sub
End Module

Output

i = 100, z = 0
i = 90, z = 3
i = 80, z = 6
i = 70, z = 9
i = 60, z = 12
i = 50, z = 15
i = 40, z = 18

This program happens to terminate because "z" exceeds 20. It is changed to 21 in the final iteration and then the loop terminates. If the "z" condition in the loop expression was removed, the loop would continue until "i" was set to -10.

Discussion

Question

How can you determine which loop is best for your VB.NET program? The Do While construct is sometimes most convenient, particularly in less common situations. Please be aware that this syntax form can easily lead to infinite loops.

The For Each loop probably leads to the fewest errors, but it cannot be used in all cases. The next best loop is For, which makes the terminating conditions and iteration expression clear to see.

For Each Loop ExamplesFor Loop Examples

Summary

The VB.NET programming language

Do While in VB.NET provides a way for you to specify a loop that will continue until the exit condition is met. This can unfortunately lead to infinite loops unless you are careful.

However:This loop construct is sometimes the clearest way of expressing your intent.


VB.NET: Loop