Section 5.6. Do While...Loop Repetition Statement


5.6. Do While...Loop Repetition Statement

The Do While...Loop repetition statement behaves like the While repetition statement. As an example of a Do While...Loop statement, consider another version of the program designed to find the first power of 3 larger than 100 (Fig. 5.6).

Figure 5.6. Do While...Loop repetition statement demonstration.

  1  ' Fig. 5.6: DoWhile.vb  2  ' Demonstration of the Do While...Loop statement.  3  Module DoWhile  4     Sub Main()  5        Dim product As Integer = 3 ' initialize product  6  7        ' statement multiplies and displays the  8        ' product while it is less than or equal to 100  9        Do While product <= 100          10           Console.Write(product & " " ) 11           product = product * 3         12        Loop                             13 14        Console.WriteLine() ' write blank line 15 16        ' print result 17        Console.WriteLine("First power of 3 " & _ 18           "larger than 100 is " & product) 19     End Sub ' Main 20  End Module ' DoWhile 

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



When the Do While...Loop statement is entered (line 9), the value of product is 3. The variable product is repeatedly multiplied by 3, taking on the values 3, 9, 27, 81 and 243, successively. When product becomes 243, the condition in the Do While...Loop statement, product <= 100, becomes false. This terminates the repetition, with the final value of product being 243. Program execution continues with the next statement after the Do While...Loop statement. Because the While and Do While...Loop statements behave in the same way, the activity diagram in Fig. 5.5 also illustrates the flow of control of the Do While...Loop repetition statement.

Common Programming Error 5.2

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




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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