while loop in C#

The while loop in C# is used to repeat a block of code as long as a condition remains true. It is useful when the number of repetitions is not known before the loop starts. This makes it different from a for loop, which is usually used when a counter or fixed range controls the repetition.

In real programs, while loops are common in input validation, menu systems, file reading, retry logic, background processing, polling, game loops, and any situation where the loop should continue until some state changes.


What Is while loop in C#?

A while loop checks a Boolean condition before each iteration. If the condition is true, the loop body runs. If the condition is false, the loop is skipped or stopped.

int count = 1;

while (count <= 5)
{
    Console.WriteLine(count);
    count++;
}

This loop prints numbers from 1 to 5. The condition is checked before every run. When count becomes 6, the condition becomes false and the loop ends.

Syntax of while loop

while (condition)
{
    // code to repeat
}

The condition must return true or false. C# does not allow integers directly as conditions, unlike some older C-style habits. This helps avoid mistakes where a number is accidentally treated as a Boolean expression.

Flow of while loop Execution

  • The condition is checked first.
  • If the condition is true, the loop body executes.
  • After the loop body, control returns to the condition.
  • The process repeats until the condition becomes false.
  • If the condition is false at the start, the loop body never runs.

This pre-check behavior is important. A while loop is not guaranteed to run even once. If you need the loop to run at least once, a do while loop may be more suitable.

while loop with User Input

A common use of while is repeating input until the user enters a valid value or an exit command. Since the number of attempts is not known in advance, while fits naturally.

string? input = "";

while (input != "exit")
{
    Console.WriteLine("Enter command or type exit:");
    input = Console.ReadLine();
}

The loop keeps running until the user types exit. This kind of loop is common in console applications, command processors, and simple interactive tools.

Sentinel-Controlled while loop

A sentinel value is a special value that tells the loop to stop. In many input loops, values are processed until a sentinel is entered. The sentinel itself is not treated as normal data.

int sum = 0;
int number = 0;

while (number != -1)
{
    Console.WriteLine("Enter number or -1 to stop:");
    number = int.Parse(Console.ReadLine() ?? "0");

    if (number != -1)
    {
        sum += number;
    }
}

Console.WriteLine(sum);

Here, -1 is the sentinel value. The loop continues until that value appears. In production code, parsing should be done with int.TryParse to avoid exceptions on invalid input.

while loop with TryParse

while works well with TryParse because validation often needs repeated attempts. The loop can keep asking until the input is valid.

int age;

Console.WriteLine("Enter your age:");
string? text = Console.ReadLine();

while (!int.TryParse(text, out age) || age < 0)
{
    Console.WriteLine("Enter a valid age:");
    text = Console.ReadLine();
}

Console.WriteLine($"Age: {age}");

This avoids crashing when the input is not a number. It also enforces a business rule that age cannot be negative.

Infinite while loop

An infinite while loop runs forever unless something inside the loop stops it. This can be useful in long-running programs, but it must be controlled carefully.

while (true)
{
    string? command = Console.ReadLine();

    if (command == "quit")
    {
        break;
    }

    Console.WriteLine($"Running: {command}");
}

The condition true never becomes false, so the loop depends on break to exit. Without a safe exit path, an infinite loop can freeze a program or waste CPU resources.

break and continue in while loop

The break statement exits the loop immediately. The continue statement skips the remaining code in the current iteration and returns to the condition check.

int i = 0;

while (i < 10)
{
    i++;

    if (i == 3)
    {
        continue;
    }

    if (i == 7)
    {
        break;
    }

    Console.WriteLine(i);
}

This loop skips 3 and stops when 7 is reached. Notice that i++ happens before continue. If the update were placed after continue, the loop could get stuck.

while loop vs for loop

Featurewhile loopfor loop
Best forUnknown number of repetitionsKnown counter-based repetitions
ConditionMain control pointOne part of the loop header
Common useInput, polling, retryingIndexing, ranges, arrays
ReadabilityGood for state-based loopsGood for counting loops

Use while when the loop depends on a changing condition or external state. Use for when the loop depends on a clear numeric counter.

State-Controlled while loop

A while loop is often controlled by a state variable. The loop keeps running while the state says the work is not finished. This is common in workflow engines, menu systems, device monitoring, and background tasks.

bool isRunning = true;

while (isRunning)
{
    string? command = Console.ReadLine();

    if (command == "stop")
    {
        isRunning = false;
    }
    else
    {
        Console.WriteLine($"Command received: {command}");
    }
}

This style is readable because the condition clearly describes the loop state. The important rule is that something inside the loop must be able to change that state, otherwise the loop may never end.

Retry Logic with while loop

Retry logic is another practical use of while. A program may try an operation multiple times until it succeeds or the retry limit is reached. This is common with network calls, temporary file access, database connections, and device communication.

int attempts = 0;
bool success = false;

while (!success && attempts < 3)
{
    attempts++;
    success = TryConnect();
}

if (!success)
{
    Console.WriteLine("Connection failed after 3 attempts");
}

This loop has two exit conditions: the operation succeeds, or the maximum number of attempts is reached. Multiple exit conditions are normal in while loops, but they should be easy to read.

Reading Data with while loop

while is useful when reading data until there is nothing left. File reading, stream reading, queue processing, and message handling often follow this pattern. The loop continues while a read operation returns data.

string? line;

while ((line = reader.ReadLine()) != null)
{
    Console.WriteLine(line);
}

The loop stops when ReadLine() returns null, meaning there is no more data to read. This is a classic condition-controlled loop because the program does not know the number of lines beforehand.

Null-Safe Input Loops

Console.ReadLine() returns string?, so modern C# code should think about null input. In many console programs, null may happen when input is redirected or closed. A null-safe loop avoids assuming that a real string is always returned.

string? input;

while ((input = Console.ReadLine()) != null)
{
    if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
    {
        break;
    }

    Console.WriteLine(input.Trim());
}

This loop handles both normal input and closed input. It also compares the exit command in a case-insensitive way, which is friendlier for users.

Debugging while loop Problems

When a while loop does not stop, inspect the condition and the variables that affect it. Usually, the loop state is not changing, the update statement is in the wrong place, or a continue statement skips the update. Adding temporary logging inside the loop can quickly reveal which value is stuck.

When a while loop stops too early, check whether the initial condition is already false or whether the loop body changes the state sooner than expected. The key is to trace the condition before and after each iteration, not only the code inside the loop body.

Choosing Clear Loop Conditions

A readable loop condition is important because it explains why the loop should continue. Conditions like while (!done), while (attempts < maxAttempts), and while (queue.Count > 0) are easy to understand. Conditions with many negations or combined rules should often be moved into a well-named Boolean variable.

bool shouldRetry = !success && attempts < maxAttempts;

while (shouldRetry)
{
    attempts++;
    success = TryConnect();
    shouldRetry = !success && attempts < maxAttempts;
}

This can be useful when the condition represents a business rule. Naming the rule makes the loop easier to maintain.

while loop with Queues

Queues are another natural match for while. A queue is processed until it becomes empty. The number of items may be different every time the program runs, so the loop depends on the queue state instead of a fixed counter.

Queue<string> jobs = new();

while (jobs.Count > 0)
{
    string job = jobs.Dequeue();
    ProcessJob(job);
}

This style is clear because the condition directly says what the loop is doing: continue while work remains. It also avoids manual index handling because the queue itself controls the next item.

For professional code, the safest while loops have a visible reason to continue and a visible way to stop. If either part is hidden, future debugging becomes harder because readers must search the whole loop to understand its lifetime.

That clarity prevents accidental endless loops and makes maintenance safer.

Keep the condition honest.

Always.

Common Mistakes with while loop

  • Forgetting to update the variable used in the condition.
  • Writing a condition that is always true by mistake.
  • Putting continue before the update step and causing an infinite loop.
  • Using while for simple counting when for would be clearer.
  • Parsing user input with Parse instead of safer TryParse.

Best Practices for while loop in C#

Use while when the number of iterations is unknown, keep the condition readable, update loop state reliably, and make exit paths obvious. If the loop depends on user input or external data, validate carefully and avoid assumptions that can trap the program in an endless loop.