Visual C# 2005 Guide
Do Loops

Do loops are executed at least once. At the end of the loop, a stopping condition is checked. If that condition evaluates to true, the loop stops. If not, it repeats until the condition is met. Care must be taken to make sure that the stopping condtion can be met otherwise the program may be trapped in an infinite loop.

The following program allows a user to type in numbers until they are sick of doing so. They then type in 999 and get to see the total of all of the numbers that they have entered.

int total = 0;
int numEntered;
Console.Write("Enter a number or 999 to finish: ");
numEntered = System.Convert.ToInt32(Console.ReadLine());
   total += numEntered;
   Console.Write("Enter a number or 999 to finish: ");
   numEntered = System.Convert.ToInt32(Console.ReadLine());
while (numEntered != 999);

Console.WriteLine("The total of the numbers entered is {0}", total);

One of the main advantages of the do loop is that its stopping condition can be expressed to allow for the number of iterations to vary at runtime depending on the value of variables.

Having A Go

  1. Write a program that generates a random number between 1 and 100. Allow the user to keep guessing the number until they have guessed the random number. If they enter a number lower than the number generated, tell them that their number is too low. Do the same if they enter a number higher than the number generated. Once they have guessed the number, tell them how many guesses they entered.