Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Lab: looping until a condition changes

A while loop repeats for as long as a condition stays true. Use it when you cannot say in advance how many turns you need.

The task

Start with a small number and double it until it passes a target, printing each step.

C#
int value = 1;
int target = 50;

while (value < target)
{
    outputLabel.Text += value + " ";
    value = value * 2;
}

The one mistake to avoid

Something inside the loop must change the condition. If nothing does, the condition stays true forever and the page never finishes loading. That is the classic infinite loop.

If a page hangs. Stop the run, look at the loop, and ask what changes between one turn and the next. If the answer is nothing, that is the bug.

You now have decisions and repeats. The next useful step is storing many values, which begins with storing many values.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.