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.