While Loop in C#: Syntax, break, continue and Input Examples (.NET 10)

Say you’re closing out the register at a Denver bike shop, and the cashier typed an unknown number of sales before typing done.

You can’t know the count up front, and that’s exactly the job of a while loop in C#: it repeats a block for as long as a condition stays true.

In this tutorial, I’ll total that register with the while loop in C# on .NET 10. You’ll write a counter loop, read input until a sentinel, validate input, use break and continue, and fix the mistakes behind most infinite loops.

The Sample Data for Our while Loop Examples

Every example works on the same seven lines a cashier typed, in this order:

#EntryWhy it’s there
1125.50Valid sale
289.99Valid sale
3abcTypo, not a number
4-20Negative, not a sale
5310.00Valid sale
6doneSentinel: stop reading
745.00Typed after done, must be ignored

A good loop skips rows 3 and 4, never reads row 7, and totals the valid sales to $525.49.

While Loop Syntax in C#

The syntax has just a keyword, a Boolean condition in parentheses and a body:

while (condition)
{
    // runs again and again while condition is true
}

C# checks the condition before each pass. If it’s false the first time, the body never runs, so a while loop runs zero or more times. That’s the key difference from a do-while loop in C#, which always runs at least once.

You’ll need the .NET 10 SDK to follow along. I run these as single-file apps with dotnet run File.cs in VS Code; see how to create a console application in Visual Studio Code if that’s new.

Method 1: Counter-Controlled while Loop (Recommended Start)

Use a counter when you know where the loop should stop, like the end of an array. Same input array, now printed with their position:

string[] entries =
    ["125.50", "89.99", "abc", "-20", "310.00", "done", "45.00"];

int i = 0;                          // 1. start the counter
while (i < entries.Length)          // 2. check before every pass
{
    Console.WriteLine($"Entry {i + 1}: {entries[i]}");
    i++;                            // 3. move toward the exit
}
Console.WriteLine($"Loop ended with i = {i}");

Output:

Entry 1: 125.50
Entry 2: 89.99
Entry 3: abc
Entry 4: -20
Entry 5: 310.00
Entry 6: done
Entry 7: 45.00
Loop ended with i = 7
while loop in C# with an int counter printing seven register entries from a string array, VS Code terminal output
The counter starts at 0, and the loop stops when i reaches entries.Length

All seven entries print, and the last line is Loop ended with i = 7.

How does this code work?

Three parts make a counter loop work. int i = 0 creates the variable before the loop, i < entries.Length is checked before every pass, and i++ moves the counter toward the exit.

When i hits 7, the condition is false and C# jumps to the line after the loop. Arrays are zero-based, so entries[i] reads index 0 through 6; my C# array guide covers that in detail.

Method 2: Read Input Until a Sentinel with a while Loop

This is where while loops shine: you don’t know how many lines are coming, only the value that ends them. Same register input, now arriving one line at a time from a TextReader:

TextReader input = new StringReader(
    "125.50\n89.99\nabc\n-20\n310.00\ndone\n45.00");   // or Console.In

int count = 0;
string? line = input.ReadLine();
while (line is not null && line != "done")
{
    count++;
    Console.WriteLine($"Read: {line}");
    line = input.ReadLine();
}
Console.WriteLine($"{count} entries before \"done\"");

Output:

Read: 125.50
Read: 89.99
Read: abc
Read: -20
Read: 310.00
5 entries before "done"

It reads five lines, prints 5 entries before "done", and never touches 45.00.

How does this code work?

StringReader stands in for the keyboard so every run is the same. Swap it for Console.In and the same loop reads what a user types, because both are a TextReader.

The first ReadLine() happens before the loop and the next one at the bottom of the body. line is not null guards against the input running out, which ReadLine() signals with null (more in checking for null values in C#).

Method 3: while Loop with break and continue

Now let’s total the sales. Same register input, but the bad rows have to be skipped instead of printed:

using System.Globalization;
CultureInfo.CurrentCulture = new("en-US");
TextReader input = new StringReader(
    "125.50\n89.99\nabc\n-20\n310.00\ndone\n45.00");
decimal total = 0;
string? line;
while ((line = input.ReadLine()) is not null)
{
    if (line == "done") break;           // stop at the sentinel
    bool ok = decimal.TryParse(line, out decimal amount);
    if (!ok || amount <= 0)
    {
        Console.WriteLine($"Skipped \"{line}\"");
        continue;                        // bad entry: next line
    }
    total += amount;
}
Console.WriteLine($"Total sales: {total:C}");

Output:

Skipped "abc"
Skipped "-20"
Total sales: $525.49
C# while loop using continue to skip invalid entries and break at the done sentinel, total $525.49 in VS Code
continue skips abc and -20; break stops at done, so 45.00 is never added

It skips abc and -20, then prints Total sales: $525.49.

How does this code work?

while ((line = input.ReadLine()) is not null) reads and tests in one step, so there’s no second ReadLine() at the bottom. That’s the common shape for reading files and streams.

break leaves the loop the moment it sees done. continue jumps straight back to the condition, skipping total += amount. decimal.TryParse returns false for abc instead of throwing, the same idea as when you convert a string to double in C#.

Note: the file sets the culture to en-US, because TryParse and :C follow the machine’s region.

Method 4: Validate Input with a while Loop

Sometimes you need one good value, and you want to ask again until you get it. Same idea, with the first three things the cashier tried for a price:

using System.Globalization;
CultureInfo.CurrentCulture = new("en-US");
TextReader input = new StringReader("abc\n-20\n125.50");

string? text = Ask();
decimal price;
while (!decimal.TryParse(text, out price) || price <= 0)
{
    Console.WriteLine($"  Not a valid price: {text}");
    text = Ask();
}
Console.WriteLine($"Saved {price:C}");

string? Ask()
{
    Console.Write("Price: ");
    string? t = input.ReadLine();
    Console.WriteLine(t);   // echo the typing
    return t;
}

Output:

Price: abc
  Not a valid price: abc
Price: -20
  Not a valid price: -20
Price: 125.50
Saved $125.50
C# while loop re-prompting for a price until decimal.TryParse succeeds, rejecting abc and -20 then saving $125.50
The loop body only runs while the input is bad

It rejects abc and -20, then prints Saved $125.50.

How does this code work?

The condition is the validation rule: keep looping while TryParse fails or the price isn’t positive. The || short-circuits, so price <= 0 is only checked after a successful parse.

If the first entry is valid, the body never runs, so the error only shows when there’s an error. Prices with thousands separators need one more step; see converting a number with commas to decimal.

Method 5: Infinite Loop with while (true) and break

while (true) runs forever unless something inside stops it. It’s the cleanest choice when a loop has more than one exit. Same register input again, but now we stop either at done or as soon as we hit a $400 daily goal:

using System.Globalization;
CultureInfo.CurrentCulture = new("en-US");
TextReader input = new StringReader(
    "125.50\n89.99\nabc\n-20\n310.00\ndone\n45.00");
decimal total = 0, goal = 400m;
while (true)
{
    string? line = input.ReadLine();
    if (line is null || line == "done") break;   // exit 1
    bool ok = decimal.TryParse(line, out decimal amount);
    if (!ok || amount <= 0) continue;            // skip
    total += amount;
    Console.WriteLine($"+{amount:C} = {total:C}");
    if (total >= goal) break;                    // exit 2
}
Console.WriteLine($"Stopped at {total:C}, goal {goal:C}");

Output:

+$125.50 = $125.50
+$89.99 = $215.49
+$310.00 = $525.49
Stopped at $525.49, goal $400.00
C# while (true) infinite loop with two break exits, stopping when the running total passes a $400 goal, VS Code output
Two exits: done (or no more input) and the $400 goal

Three sales print, ending at +$310.00 = $525.49, then Stopped at $525.49, goal $400.00.

How does this code work?

Each exit is an explicit break. The goal check fires after 310.00, so the loop never reaches done here.

for ( ; ; ) does the same job, but while (true) reads better. For menus, put a switch case in C# inside the loop and break out on Quit.

Pro Tip: make sure every path through a while (true) body can reach a break, return or throw.

While vs do-while vs for Loop in C#: What’s the Difference?

Here are all three on the same starting point, an empty stock count:

int stock = 0;

while (stock > 0)
    Console.WriteLine("while: never printed");

do
    Console.WriteLine("do-while: printed once");
while (stock > 0);

for (int day = 1; day <= 3; day++)
    Console.Write($"day {day} ");
Console.WriteLine("<- for");

Output:

do-while: printed once
day 1 day 2 day 3 <- for

The while loop prints nothing, because stock > 0 is false on the first check. The do-while prints once before it checks. The for loop counts days 1 to 3.

whiledo-whilefor
Condition checkedBefore each passAfter each passBefore each pass
Minimum runs010
Best forUnknown count, sentinel, inputMenus, run-at-least-onceKnown count, index
Counter scopeOutside the loopOutside the loopInside the loop

When I need the index and know the count, I write a for loop in C#. To read every item of a collection, a foreach loop is shorter and can’t go out of range.

Common while Loop Mistakes (and How to Fix Them)

Off-by-One: <= Instead of <

Same input array, cut to three. One extra = reads one item past the end:

string[] entries = ["125.50", "89.99", "abc"];

int i = 0;
while (i <= entries.Length)         // bug: should be <
{
    Console.WriteLine(entries[i]);
    i++;
}

Output (unhandled exception):

125.50
89.99
abc
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Program.<Main>$(String[] args) in C:\DotNetDemo\WhileLoopDemo\OffByOne.cs:line 6
C# while loop off-by-one error using <= entries.Length throwing IndexOutOfRangeException in the VS Code terminal
The fourth pass asks for entries[3], which doesn’t exist

The three entries print, then IndexOutOfRangeException. Use i < entries.Length; the last valid index is always Length - 1.

Forgetting the Increment

Drop the i++ and the condition never changes, so this prints 125.50 until you press Ctrl+C:

int i = 0;
while (i < entries.Length)
    Console.WriteLine(entries[i]);   // no i++: runs forever

Which while Loop Pattern Should You Use?

SituationPattern
Known end, like an array lengthMethod 1: counter loop (or a for loop)
Read until a stop value or end of inputMethod 2: sentinel loop
Skip bad rows, stop earlyMethod 3: continue and break
Need one valid value from the userMethod 4: re-prompt loop
Several ways to finishMethod 5: while (true) with break

Things to Keep in Mind

  • The condition is checked first. A false condition means zero runs; use do-while when you need one.
  • Something must change. Every pass should move the counter, read input or flip a flag.
  • break only exits the innermost loop. In nested loops, use a flag or move the loops into a method and return.
  • Watch <= with arrays. The last index is Length - 1.
  • Set the culture when parsing money. TryParse and :C follow the machine’s region.

Want more practice with loops? These programs all use one:

Frequently Asked Questions

What is a while loop in C#?

It’s an iteration statement that runs its body as long as a Boolean condition is true. The condition is checked before each pass, so the body can run zero times.

What is the difference between while and do-while in C#?

A while loop checks its condition before the body and runs zero or more times. A do-while checks after the body and runs one or more times, as the iteration statements reference on Microsoft Learn explains.

How do I stop an infinite while loop in C#?

Inside the code, use break, return or throw on a condition that will eventually be met. In a running console app, press Ctrl+C to end the process.

Does break exit all nested while loops?

No. break ends only the innermost loop that contains it. To leave outer loops, set a flag that their conditions check, or put the loops in a method and use return.

Can a while loop read user input until the user types a word?

Yes. Read with Console.ReadLine() and loop while the line isn’t null and isn’t your stop word, such as done. Reading a TextReader lets you test the same loop with a StringReader.