do...while Repetition Statement

The do...while repetition statement is similar to the while statement. In the while, the application 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 do...while statement tests the loop-continuation condition after executing the loop's body; therefore, the body always executes at least once. When a do...while statement terminates, execution continues with the next statement in sequence. Figure 6.7 uses a do...while (lines 1115) to output the numbers 110.

Figure 6.7. do...while repetition statement.

1 // Fig. 6.7: DoWhileTest.cs 2 // do...while repetition statement. 3 using System; 4 5 public class DoWhileTest 6 { 7 public static void Main( string[] args ) 8 { 9 int counter = 1; // initialize counter 10 11 do 12 { 13 Console.Write( "{0} ", counter ); 14 counter++; 15 } while ( counter <= 10 ); // end do...while 16 17 Console.WriteLine(); // outputs a newline 18 } // end Main 19 } // end class DoWhileTest  

1 2 3 4 5 6 7 8 9 10

Line 9 declares and initializes control variable counter. Upon entering the do...while statement, line 13 outputs counter's value, and line 14 increments counter. Then the application 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 in the do...while (line 13). If the condition is false, the loop terminates, and the application continues with the next statement after the loop.

Figure 6.8 contains the UML activity diagram for the do...while 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.4). It is not necessary to use braces in the do...while repetition statement if there is only one statement in the body. However, most programmers include the braces, to avoid confusion between the while and do...while statements. For example,

while ( condition )

is normally the first line of a while statement. A do...while statement with no braces around a single-statement body appears as:

do statement while ( condition );

which can be confusing. A reader may misinterpret the last linewhile( condition );as a while statement containing an empty statement (the semicolon by itself). Thus, a do...while statement with one body statement is usually written as follows:

do { statement } while ( condition );

Figure 6.8. do...while repetition statement UML activity diagram.

Error Prevention Tip 6 4

Always include braces in a do...while statement, even if they are not necessary. This helps eliminate ambiguity between while statements and do...while statements containing only one statement.

switch Multiple Selection Statement

Категории