C Sharp

The do/while Statement

Looking back at the syntax for the while statement, you can see the possibility for one problem. The Boolean-expression is evaluated beforethe embedded-statement is executed. For this reason, the application in the previous section initialized the correctGuess and userQuit variables to false to guarantee that the while loop would be entered. From there, those values are controlled by whether the user correctly guesses the number or quits. However, what if we want to make sure that the embedded-statement always executes at least once without having to set the variables artificially? This is what the do/while statement is used for.

The do/while statement takes the following form: -

    do
    embedded-statement
    while ( Boolean-expression )

Because the evaluation of the while statement's Boolean-expression occurs afterthe embedded-statement, you're guaranteed that the embedded-statement will be executed at least one time. The number-guessing application rewritten to use the do/while statement appears on the following page.

using System;
class DoWhileApp
{
    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 = -1;
        bool userHasNotQuit = true;
        do
        {
            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))
                userHasNotQuit = false;
            else
            {
                userGuess = inputString.ToInt32();
                Console.WriteLine
                    ("The correct number was {0}\n", correctNumber);
            }
        } while (userGuess != correctNumber
            && userHasNotQuit);
        if (userHasNotQuit
            && userGuess == correctNumber)
        {
            Console.WriteLine("Congratulations!");
        }
        else // wrong answer!
        {
            Console.WriteLine("Maybe next time!");
        }
    }
}

The functionality of this application will be the same as the while sample. The only difference is how the loop is controlled. In practice, you'll find that the while statement is used more often than the do/while statement. However, because you can easily control entry into the loop with the initialization of a Boolean variable, choosing one statement over the other is a choice of personal preference.