Visual C# Guide
While Loops

While loops only execute their blocks of code if a condition is met. Unlike do loops, the stopping condition can be met on the first iteration. This is a similar program to the one on the previous page. Compare the two programs.

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

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

Having A Go

  1. Rewrite the program you wrote for the exercise on the previous page to use the while statement.