Charlie Calvert on Elvenware

Writing Code and Prose on Computers

Elvenware

Exiting a While Loop

Think of it like this. A child might ask: "How long do I have to stand here washing the dishes?" The answer is sometimes something like this: "You need to stand there until the dishes are done." At a gym someone might ask: "How long are you going to stay on the elliptical trainer?" And the answer might be: "I'll stay here until 1 o'clock."

In these cases, some activity is being repeated until some condition is true. One keeps washing dishes until all the dishes are clean. One keeps running in place until it is one o'clock.

One can also stop a repeated activity once something is false. "I will sleep until it is no longer dark." The person sleeps until dark is false. "I will keep dieting until I am no longer over weight." I will diet until fat is false.

The same is true of a loop. The following code prompts the user for a number, and then writes "I'm in a loop" until it counts down from the number to zero. It exits the loop when the statement x is smaller than or equal to zero is true.

Console.Write("How long should I keep doing this: ");
int x = int.Parse(Console.ReadLine());            
do
{
    Console.WriteLine("I'm in a loop {0}", x--);     
} while (x <= 0);