1.15 Breaking Out of a Loop Control Body

 <  Day Day Up  >  

You need to repeatedly execute statements in a block but break out of the loop based on a certain event.


Technique

There are two ways to break out of a loop statement in the middle of a loop body. The first is by using the break keyword. Using it will break out of the loop entirely, and execution will begin at the statement following your loop block. The second way is to use the continue keyword, which will cause your application to skip the rest of the loop body but then reevaluate the loop conditional and possibly enter the loop again.

Comments

Although the break and continue keywords are rarely used, sometimes they might prove to be the only alternative. As mentioned earlier, use a break statement when you are within the loop body and need to exit the loop entirely. You simply exit the loop, and the program continues execution at the statement following the loop body. An example is a modification of the game in Listing 1.9 in which the loop will exit if the user enters a number that is one less than the randomly generated number.

Listing 1.10 Using the break Keyword to Make the Number-Guessing Game a Little Easier
 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-1 == number )             break;  // close enough         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} tries!", guesses ); } 

If you want to instead make the game a little harder, you could set a difficulty value and use the continue keyword to bypass the statements that tell the user whether her guess is too high or too low. Yes, using an if statement for these cases seems like a more logical choice, which is a reason why we said the break and continue statements are rarely used.

 <  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