Iteration Statements

In a VB.NET method, you will find many situations in which you want to do the same thing again and again, perhaps slightly changing a value each time you repeat the action. This is called iteration or looping. Typically, you'll iterate (or loop) over a set of items, taking the same action on each. This is the programming equivalent to an assembly line: take a hundred car bodies and put a windshield on each one as it comes by.

VB.NET provides an extensive suite of iteration statements , including Do and For.

The Do Loop

The semantics of a Do loop are "Do this work while a condition is true" or "Do this work until a condition becomes true." You can test the condition either at the top or at the bottom of the loop. If you test at the bottom of the loop, the loop will execute at least once.

The Do loop can even be written with no conditions; in which case, it will execute indefinitely, until it encounters an Exit Do statement.

Do loops come in the following flavors:

Do While BooleanExpression
   statements
Loop

Do Until BooleanExpression
    statements
Loop

Do
    statements
Loop while BooleanExpression

Do
   statements
Loop until BooleanExpression

Do
    statements
Loop

In each case, the BooleanExpression can be any expression that evaluates to a Boolean value of True or False.

Do While

The first kind of Do loop, Do While, executes only while the BooleanExpression returns True, as shown in Example 16-9.

Example 16-9. Using Do While

Option Strict On Module Module1 Sub Main() Dim counterVariable ...

Get Programming Visual Basic 2005 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.