Using do Loops


Using do Loops

Do loops and while loops are closely related . Do loops, like while loops, also execute statements a number of times. However, a do loop always executes once regardless of whether the expression to test is true or false.

To write a do loop:

  1. Type do .

  2. In the next line type an open curly bracket { .

  3. Type the statements to execute in the loop.

  4. Remember to change the variable used for the expression in step 8 so that at some point the expression will result in false and end the loop. For example: count++;

  5. Type a close curly bracket } .

  6. Type while .

  7. Type an open parenthesis ( .

  8. Type an expression that results in true or false. For example: count < 20 . The variables that are going to be used in the while at the end of the do statement must be declared before the do in step 1. For example: int count=1;

  9. Type a close parenthesis ) .

  10. Type a semicolon ; ( Figure 3.38 ).

    Figure 3.38 No matter how hard you try to put kids to bed on time, they always have an unlimited amount of excuses. Some would argue the above will result in an endless loop. Nonetheless, the code attempts to put the kids to bed first before finding out if there are excuses, then continues to try while the excuses continue, if they ever stop then the loop ends. This code came courtesy of my wife.
     void NightRoutine() {    string childExcuse="";  do   {  childExcuse = PutKidsInBed();  } while( childExcuse != "" );  } 


C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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