Visual Basic.NET 2008 > Programming Fundamentals

While...End While Loop Statement in Visual Basic 2008

The While. . .End While loop executes a block of statements as long as a condition is True. The loop has the following syntax:

While condition
statement-block
End While

If condition is True, all statements in the bock are executed. When the End While statement is reached, control is returned to the While statement, which evaluates condition again. If condition is still True, the process is repeated. If condition is False, the program resumes with the statement following End While.

The loop in Listing 3.5 prompts the user for numeric data. The user can type a negative value to indicate he's done entering values and terminate the loop. As long as the user enters positive numeric values, the program keeps adding them to the total variable.

Listing 3.5: Reading an Unknown Number of Values

Dim number, total As Double
number = 0
While number => 0
total = total + number
number = InputBox("Please enter another value")
End While

I've assigned the value 0 to the number variable before the loop starts because this value isn't negative and doesn't affect the total.

Sometimes, the condition that determines when the loop will terminate can't be evaluated at the top of the loop. In these cases, we declare a Boolean value and set it to True or False from within the loop's body. Here's the outline of such a loop:

Dim repeatLoop As Boolean
repeatLoop = True
While repeatLoop
{ statements }
If condition Then
repeatLoop = True
Else
repeattLoop = False
End If
End While

You may also see an odd loop statement like the following one:

While True
{ statements }
End While

It's also common to express the True condition as follows:

While 1 = 1

This seemingly endless loop must be terminated from within its own body with an Exit While statement, which is called when a condition becomes True or False. The following loop terminates when a condition is met in the loop's body:

While True
{ statements }
If condition Then Exit While
{ more statements }
End While

Table of Contents





     
 
W3computing.com Copyright 2011 All Rights Reserved
 
  Home | Useful links | Contact us