Using while Loops


Using while Loops

There are various ways of executing code a certain number of times. While loops enable you to loop until a certain condition is met.

To write a while loop:

  1. The variables that are going to be used in the while statement must be declared first. For example: int count = 1;

  2. Type while followed by an open parenthesis ( .

  3. Type an expression that results in true or false. For example: count < 10 .

  4. Type a close parenthesis ) .

  5. Type an open curly bracket { .

  6. Type the statements that you wish to execute while the expression is true.

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

  8. Type a close curly bracket } ( Figure 3.36 ).

    Figure 3.36 The loop will continue as long as the start number isn't greater than the end number. Notice that the loop won't execute at all if the caller sends a start number greater that the end number to begin with.
     void GenerateEvenNumbers(int startnum, int endnum) {  while (startnum <= endnum)   {  Response.Write(startnum + "<br>");      startnum+=2;  }  } 

graphics/tick.gif Tips

  • Writing the expression for the while loop is similar to writing an expression for an if statement. You can combine clauses with && and ( Figure 3.37 ).

    Figure 3.37 The conditional expression supports and statements and or statements just like if statements. You can put any expression in the parenthesis that evaluates to true or false.
     void ForwardToVoiceMail(int maxRings) {    int rings = 0;    bool answered = HasPersonAnswered();    while (  rings < maxRings && answered == false  )    {      Ring();      rings++;      answered = HasPersonAnswered();    } } 
  • While loops continue to execute until the expression becomes false. Forgetting to change the variable in the expression is a common mistake that results in an endless loop.




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