Visual Basic 2005 for Programmers (2nd Edition)

5.7. Do Until...Loop Repetition Statement

Unlike the While and Do While...Loop repetition statements, the Do Until...Loop repetition statement tests a condition for falsity for repetition to continue. Statements in the body of a Do Until...Loop are executed repeatedly as long as the condition (known as the loop-termination condition) evaluates to false. The program of Fig. 5.7 finds the first power of 3 larger than 100 by using a Do Until...Loop repetition statement.

Figure 5.7. Do Until...Loop repetition statement demonstration.

1 ' Fig. 5.7: DoUntil.vb 2 ' Demonstration of the Do Until...Loop statement. 3 Module DoUntil 4 Sub Main() 5 Dim product As Integer = 3 6 7 ' find first power of 3 larger than 100 8 Do Until product > 100 9 Console.Write(product & " " ) 10 product = product * 3 11 Loop 12 13 Console.WriteLine() ' write blank line 14 15 ' print result 16 Console.WriteLine("First power of 3 " & _ 17 "larger than 100 is " & product) 18 End Sub ' Main 19 End Module ' DoUntil

3 9 27 81 First power of 3 larger than 100 is 243

Once again, the activity diagram of Fig. 5.5 illustrates the flow of control in the Do Until...Loop repetition statement shown in Fig. 5.7. This time, however, we focus on the leftmost guard conditionproduct > 100the loop-termination condition for our control statement. Because we are using a Do Until...Loop statement, the statement's actions (lines 910) are performed when the statement's loop-termination condition is false (i.e., product is less than or equal to 100). When the loop-termination condition (product > 100, the leftmost guard condition) is true the statement exits.

Common Programming Error 5.3

Failure to provide the body of a Do Until...Loop statement with an action that eventually causes the loop-termination condition in the Do Until...Loop to become true creates an infinite loop.

Категории