while Loops

Loops repeat code. A while loop keeps going as long as a condition is true, which suits situations where you don't know in advance how many repetitions you'll need — reading input until it's valid, waiting for a value to reach a target, processing until a list is empty.

while

The condition is checked before each pass. If it's false at the start, the body never runs:

C#
int countdown = 5;

while (countdown > 0)
{
    Console.Write(countdown + " ");
    countdown--;
}
Console.WriteLine("Lift-off!");
Output
5 4 3 2 1 Lift-off!

Something inside the loop must eventually make the condition false — here countdown--. Forget it, and the loop runs forever. (Press Ctrl+C to stop a runaway program.)

When the count isn't known

How many years until savings double at 5% interest? You can't tell without running the calculation, so while is the natural choice:

C#
decimal balance = 1000m;
int years = 0;

while (balance < 2000m)
{
    balance *= 1.05m;
    years++;
}

Console.WriteLine($"{years} years, final balance {balance:F2}");
Output
15 years, final balance 2078.93

do-while

A do-while loop checks its condition after each pass, so the body always runs at least once. That fits menus and prompts, which should be shown before you know whether to repeat them:

C#
string? choice;
do
{
    Console.WriteLine("1) Play  2) Settings  Q) Quit");
    Console.Write("> ");
    choice = Console.ReadLine()?.Trim().ToUpper();
    Console.WriteLine($"You chose {choice}");
} while (choice is not null && choice != "Q");
Input
1
2
q
Output
1) Play  2) Settings  Q) Quit
> You chose 1
1) Play  2) Settings  Q) Quit
> You chose 2
1) Play  2) Settings  Q) Quit
> You chose Q

Note the semicolon after the final while (...) — it's required in a do-while.

break and continue

break leaves the loop immediately. continue skips the rest of the current pass and jumps to the next condition check:

C#
int n = 0;
while (true)
{
    n++;
    if (n % 3 == 0)
    {
        continue;        // skip multiples of 3
    }
    if (n > 10)
    {
        break;           // stop completely
    }
    Console.Write(n + " ");
}
Console.WriteLine();
Output
1 2 4 5 7 8 10

while (true) with a break inside is a common, readable pattern when the exit test belongs in the middle of the loop.

Processing until something runs out

Loops often consume a collection or input until nothing is left. Here a queue of jobs is processed one at a time (queues are covered in lesson 29):

C#
var jobs = new Queue<string>(["resize image", "send email", "write log"]);

while (jobs.Count > 0)
{
    string job = jobs.Dequeue();
    Console.WriteLine($"Running: {job} ({jobs.Count} left)");
}
Output
Running: resize image (2 left)
Running: send email (1 left)
Running: write log (0 left)

Reading all input lines

Because Console.ReadLine returns null at the end of input, a while loop can read every line — perfect for processing a file piped into your program (dotnet run Program.cs < data.txt):

C#
int lineCount = 0, wordCount = 0;
string? line;

while ((line = Console.ReadLine()) is not null)
{
    lineCount++;
    wordCount += line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
}

Console.WriteLine($"{lineCount} lines, {wordCount} words");
Input
The quick brown fox
jumps over

the lazy dog
Output
4 lines, 9 words

The assignment inside the condition reads a line and checks it in one step.

Try it yourself

The Collatz sequence: if a number is even, halve it; if odd, multiply by 3 and add 1. It always seems to reach 1 eventually. Count the steps for a few starting values.

Try it yourself · Program.cs
Edit the code, copy it into Program.cs and run it with dotnet run Program.cs (.NET 10 or later). How to set up .NET
Output
27 reaches 1 after 111 steps (peak 9232).