1.14 Using Looping Control Structures

 <  Day Day Up  >  

You need to continuously perform a set of actions a certain number of times or until a certain condition becomes false.


Technique

C# contains several different looping control structures to handle different cases. You use a for statement if you need to run a loop a set number of times. If you need to execute a block of statements while an expression remains true, use a while loop. Choose a do / while statement if you need to execute a block of statements at least once regardless of any pre-existing conditions and then continuously while an expression remains true.

Comments

In the last recipe, you saw how you can use if statements to execute blocks of code based on certain conditions. However, you could only execute that block of code one time. Looping control structures allow you to execute blocks of code several times and stop either when an expression finally evaluates to false or when you explicitly break out of the loop somewhere within the body of the loop using the C# keyword break . Using loops requires care because the conditional statement to test whether the loop should continue might never become false, which means the program gets stuck in an endless loop. All three of the looping statements covered here have the possibility of continuing forever.

You generally use the for loop when you want to execute a block of code a certain amount of times. An index variable associated with the loop keeps count of the iterations that have occurred and if you tested it to see whether the loop should finish executing. The for statement contains three sections as shown in Listing 1.7. The first part is for initialization. In most cases, you initialize the variable used to control the for loop. However, you are free to initialize other variables or even call methods as long as they are separated by commas. The second component of the for statement is the conditional expression you want to evaluate. If the expression remains true, the for loop body executes. Finally, the last field of the for loop is for changing the variables associated with the conditional statement by either incrementing or decrementing the loop counter, for example.

Listing 1.7 Using a for Statement to Loop and Calculate the Factorial of a Number
 static void ComputeFactorial() {     ulong loopCount = 0;     ulong factorial = 1;     Console.Write( "Enter an integer between 1 and 50: " );     loopCount = UInt64.Parse( Console.ReadLine() );     for( ulong i = loopCount; i > 0; i-- )     {         factorial *= i;     }     Console.WriteLine( "{0}! = {1}", loopCount, factorial ); } 

The while and do / while statements are quite similar in that both loop while a certain condition holds true. Once that condition evaluates to false, the loop is exited and the next statement following the loop block is executed. The major difference between the two loop structures is that the do / while statement's code block is guaranteed to execute at least once. The while statement appears at the end of the code block, as shown in Listing 1.8, instead of at the beginning as with the while statement.

Listing 1.8 Using the do / while Statement to Control Program Flow
 static void NumberGuessGame() {     int guess, number, guesses = 0;     number = new Random((int)DateTime.Now.Ticks).Next( 0, 10 );     do     {         ++guesses;          Console.Write( "Enter a number between 1 and 10: " );          guess = Int32.Parse( Console.ReadLine() );         if( guess < number )             Console.WriteLine( "Too low. Pick a higher number" );         else if ( guess > number )             Console.WriteLine( "Too high. Pick a lower number" );     } while (guess != number );     Console.WriteLine( "You are correct and it only took you "+      "{0} guesses!", guesses ); } 

A while statement might never run if the condition is always false during the execution of a program because the condition is evaluated before the code block is entered. If the initial condition is false , then the block is skipped and the program continues after that point. Listing 1.9 shows a while loop being used to create a countdown timer.

Listing 1.9 The while Statement
 using System; namespace _14_Looping {     class Game     {          [STAThread]         static void Main(string[] args)         {             WaitForNewMinute();             NumberGuessGame();         }         static void WaitForNewMinute()         {             int sec = -1;             Console.Write( "The game will start in " );             while( DateTime.Now.Second != 0 )             {                 if( sec != DateTime.Now.Second )                 {                     sec = DateTime.Now.Second;                     Console.Write( "...{0}", 60-DateTime.Now.Second );                 }             }             Console.WriteLine();         }        } } 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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