VB.NET Do While Loop

Do keyword

How can you use the Do While loop in your VB.NET program? This syntax form provides a way to continue iterating while one or more conditions are true. We take a peek at the Do While construct in this language.

This VB program demonstrates the Do While loop syntax. It increments and decrements.

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. In each iteration, we change the values of these variables: i is decremented by 10 and z is incremented by 3.

Program that uses Do While loop [VB.NET]

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

Output of the program. 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.

Choose loops

Question and answer

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 lead to infinite loops very easily! You must be careful to test the terminating conditions.

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 very clear to see.

For Each Loop Examples For 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 very careful. However, this loop construct is sometimes the clearest way of expressing your program.

VB.NET Tutorials
.NET