Breaking Out of Infinite Loops
Another use for the break statement is to create an infinite loop in which control is transferred out of the loop only by a break statement being reached. The following example illustrates a method of writing the number-guessing game presented earlier in the chapter with a break statement used to quit the loop once the user enters the letter Q. Notice that I changed the while statement to while(true) such that it will not end until a break statement is encountered.
using System;
class InfiniteLoopApp
{
const int MIN = 1;
const int MAX = 10;
const string QUIT_CHAR = "Q";
public static void Main()
{
Random rnd = new Random();
double correctNumber;
string inputString;
int userGuess;
bool correctGuess = false;
bool userQuit = false;
while(true)
{
correctNumber = rnd.NextDouble() * MAX;
correctNumber = Math.Round(correctNumber);
Console.Write
("Guess a number between {0} and {1}...({2} to quit)",
MIN, MAX, QUIT_CHAR);
inputString = Console.ReadLine();
if (0 == string.Compare(inputString, QUIT_CHAR, true))
{
userQuit = true;
break;
}
else
{
userGuess = inputString.ToInt32();
correctGuess = (userGuess == correctNumber);
if ((correctGuess = (userGuess == correctNumber)))
{
break;
}
else
{
Console.WriteLine
("The correct number was {0}\n", correctNumber);
}
}
}
if (correctGuess && !userQuit)
{
Console.WriteLine("Congratulations!");
}
else
{
Console.WriteLine("Maybe next time!");
}
}
}
One last point: I could have used an empty for statement here with the form for (;;) instead of while(true). They work the same, so it comes down to a matter of taste.