Do While LoopsFlavor Two


Do While Loops”Flavor Two

The second type of Do - While loop has the following syntax:

  Do   DoWhileStatementBlock   Loop While   Expression1  

The only real change is that the test on Expression1 is moved to the bottom of the loop. The logic, however, is still the same. If Expression1 is True, another iteration of the loop is made. However, having the test of Expression1 at the bottom of the loop has one important implication : The loop is always executed at least one time.

When Expression1 is at the bottom of the loop, the statements in the loop block are executed before the test on Expression1 is evaluated. For example, suppose that we have a fire alarm system that calls a function that reads all the fire sensors in the building. If there is no fire, the call returns . If there is a fire, the call returns the sensor number where the fire is located. Now consider the following code fragment:

 Dim Fire As Integer  Fire = CheckSensors() Do While Fire = 0     Fire = CheckSensors()     If Fire Then       CallSecurity()     End If Loop 

Even though this code is a little simplistic, it does illustrate the point. With the preceding Do - While loop, what if the first call to CheckSensors() does in fact find a fire? Because Fire is nonzero, the loop is never executed and CallSecurity() is never called.

So, we change the code to

 Dim Fire As Integer  Fire = CheckSensors() Do   If Fire Then     CallSecurity()   End If   Fire = CheckSensors() Loop While Fire = 0 

In this situation, even though Fire is already nonzero, we enter the loop and, hence, make the call to CallSecurity() . The only difference between the two versions is that the test on whether to execute the loop is made at the bottom of the loop rather than the top.

As an exercise, you could rewrite the coin toss program to use the Do While with the test at the bottom. What changes would you have to make in the code?



Visual Basic .NET. Primer Plus
Visual Basic .NET Primer Plus
ISBN: 0672324857
EAN: 2147483647
Year: 2003
Pages: 238
Authors: Jack Purdum

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net