6.7 dowhile Iteration Statement

The dowhileiteration statement is similar to the while statement. In the while, the app tests the loop-continuation condition at the beginning of the loop, before executing the loop’s body. If the condition is false, the body never executes. The dowhile statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once. When a dowhile statement terminates, execution continues with the next statement in sequence. Figure 6.7 uses a dowhile (lines 11–15) to output the numbers 1–10.

Fig. 6.7 do...while iteration statement.

Alternate View

  1    // Fig. 6.7: DoWhileTest.cs
  2    // do...while iteration statement.
  3    using System;
  4
  5    class DoWhileTest
  6    {
  7       static void Main()
  8       {
  9          int counter = 1; // initialize counter
 10
 11          do                                            
 12          {                                             
 13             Console.Write($"{counter}   ");             
 14             ++counter;
 15          } while (counter <= 10); // required semicolon
 16
 17          Console.WriteLine();
 18      }
 19    }

1   2    3    4     5   6   7   8   9   10

Line 9 declares and initializes control variable counter. Upon entering the dowhile statement, line 13 outputs counter’s value, and line 14 increments counter. Then the app evaluates the loop-continuation test at the bottom of the loop (line 15). If the condition is true, the loop continues from the first body statement (line 13). If the condition is false, the loop terminates, and the app continues with the next statement after the loop (line 17).

UML Activity Diagram for the dowhile Iteration Statement

Figure 6.8 contains the UML activity diagram for the dowhile statement. This diagram makes it clear that the loop-continuation condition is not evaluated until after the loop performs the action state at least once. Compare this activity diagram with that of the while statement (Fig. 5.7).

Fig. 6.8 dowhile iteration statement UML activity diagram.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset