do while loop in C#

The do while loop in C# is used to repeat a block of code while a condition is true, but with one important difference from a normal while loop: a do while loop always runs at least once. The condition is checked after the loop body, not before it.

This makes do while useful when the program must perform an action first and then decide whether to repeat it. Menu systems, input prompts, retry flows, confirmation dialogs, and simple game loops often fit this pattern.


What Is do while loop in C#?

A do while loop executes the loop body first and checks the condition afterward. If the condition is true, the loop repeats. If the condition is false, the loop stops after that first execution.

int count = 1;

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

This prints numbers from 1 to 5. The body runs first, then the condition count <= 5 is checked. The semicolon after the while condition is required in a do while loop.

Syntax of do while loop

do
{
    // code to repeat
}
while (condition);

The loop body appears before the condition. This structure makes the intent clear: execute the block once, then decide whether it should run again.

Flow of do while loop Execution

  • The loop body runs first.
  • The condition is checked after the body.
  • If the condition is true, the loop repeats.
  • If the condition is false, the loop stops.
  • The loop body always runs at least once.

This after-check behavior is the main reason to use do while. If the loop body should not run until a condition is already true, use a normal while loop instead.

do while loop with User Input

User input is one of the clearest uses of do while. The program must ask for input at least once, then repeat if the input is invalid or if the user wants to continue.

string? input;

do
{
    Console.WriteLine("Enter yes to continue or no to stop:");
    input = Console.ReadLine();
}
while (input != "no");

The prompt appears before the condition is checked. That makes sense because the program needs user input before it can know whether to repeat.

Menu Example with do while

Console menus often use do while because the menu should display at least once. After the user chooses an option, the program can decide whether to show the menu again.

string? choice;

do
{
    Console.WriteLine("1. Add item");
    Console.WriteLine("2. View items");
    Console.WriteLine("3. Exit");
    choice = Console.ReadLine();

    switch (choice)
    {
        case "1":
            Console.WriteLine("Adding item");
            break;
        case "2":
            Console.WriteLine("Viewing items");
            break;
    }
}
while (choice != "3");

The menu is shown first, and it continues until the user selects option 3. This is more natural than a pre-check loop because there is no valid menu choice before the menu appears.

Input Validation with do while

do while is useful for validation when the program must ask at least once and repeat until valid input is received.

int number;
bool isValid;

do
{
    Console.WriteLine("Enter a positive number:");
    string? text = Console.ReadLine();
    isValid = int.TryParse(text, out number) && number > 0;
}
while (!isValid);

Console.WriteLine($"Accepted number: {number}");

This avoids invalid parsing and keeps asking until the user enters a positive integer. The Boolean variable isValid makes the condition easy to understand.

do while vs while loop

Featuredo whilewhile
Condition checkAfter loop bodyBefore loop body
Minimum runsAt least onceZero or more times
Best forMenus, prompts, retry after first attemptState-based loops and pre-checked conditions
Common riskRuns once even when condition would be falseMay never run if condition starts false

The difference is not small. Choose do while only when one execution is required. If running once would be dangerous or incorrect, use while.

Infinite do while loop

A do while loop can also be infinite if its condition always remains true. This should be done only when there is a clear exit path such as break.

do
{
    string? command = Console.ReadLine();

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

    Console.WriteLine(command);
}
while (true);

This loop depends on the break statement to stop. Without it, the loop would continue forever.

Why do while Is Called an Exit-Controlled Loop

A do while loop is often called an exit-controlled loop because the condition is checked at the end. The loop does not ask whether it should enter. It enters first, performs the work, and then asks whether it should continue.

This is useful when the first execution produces the information needed for the condition. For example, a program cannot know whether user input is valid until it has asked the user at least once. In that case, checking the condition after the prompt is logical.

Use do while when the first attempt is part of the logic, not an accident.

Retry Logic with do while

Retry flows can use do while when the program should try the operation first and then decide whether another attempt is needed. This is common when making a connection, reading from a temporary resource, or asking the user to retry after failure.

int attempts = 0;
bool success;

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

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

This code guarantees at least one save attempt. After that, it repeats only while the operation is unsuccessful and the attempt limit has not been reached. The condition has both a success check and a safety limit.

do while with Confirmation Prompts

Confirmation prompts are another practical use case. The program asks the user a question first, then repeats only if the answer is not acceptable. This creates a user-friendly loop without duplicating the first prompt outside the loop.

string? answer;

do
{
    Console.WriteLine("Do you want to continue? yes/no");
    answer = Console.ReadLine()?.Trim().ToLower();
}
while (answer != "yes" && answer != "no");

Console.WriteLine($"Answer: {answer}");

The loop repeats only when the user enters something other than yes or no. Trimming and lowercasing input makes the prompt more tolerant of normal user typing.

do while and Variable Scope

Variables used in the condition often need to be declared before the do block. This is because the condition appears after the block but must still be able to access the value. If a variable is declared only inside the block, it may not be available in the condition depending on the exact scope.

string? command;

do
{
    command = Console.ReadLine();
}
while (command != "exit");

This structure keeps the loop control variable visible to both the body and the condition. Clear scope avoids confusing compiler errors and makes the loop easier to read.

When Not to Use do while

Do not use do while when the loop body may be unsafe or incorrect before checking the condition. For example, if a collection may be empty, processing an item before checking whether an item exists can cause errors. In that case, a normal while loop or foreach loop is safer.

The question to ask is simple: should this code definitely run once? If the answer is no, avoid do while. The guarantee of one execution is powerful, but it can also be dangerous when the first execution depends on a valid precondition.

do while with break and continue

break and continue work in a do while loop just like they work in other loops. break exits the loop immediately. continue skips the remaining statements and moves directly to the condition check at the bottom.

int number = 0;

do
{
    number++;

    if (number == 2)
    {
        continue;
    }

    if (number == 5)
    {
        break;
    }

    Console.WriteLine(number);
}
while (number < 10);

Because continue jumps to the condition check, make sure the loop state is already updated before it. Otherwise, the loop may repeat forever with the same value.

Debugging do while Loops

When debugging a do while loop, remember that the body runs before the condition. If something unexpected happens once even though the condition looks false, that is normal behavior for this loop type. Check whether do while was the correct loop choice.

If the loop never stops, inspect the variables used in the condition. Usually, the input is not normalized, the state variable is not updated, or the condition is written with the wrong logical operator.

Real-World Rule for do while

A good real-world rule is to use do while only when the first action is mandatory. Showing a menu, asking a question, and making one retryable attempt are good examples. Processing a collection, reading a file, or using a resource that may not exist usually needs a pre-check loop instead.

This rule keeps the loop intentional. The post-condition design should match the problem, not just personal style.

When the loop condition is written after the body, readers expect the first run to be deliberate. If that expectation is not true, the loop becomes misleading and should be replaced with a safer structure.

That choice protects correctness and readability.

Always.

Common Mistakes with do while loop

  • Forgetting the semicolon after the while condition.
  • Using do while when the body should not always run once.
  • Writing a condition that never becomes false.
  • Putting too much logic inside the loop instead of using methods.
  • Using unclear variable names for loop control.

Best Practices for do while loop in C#

Use do while when one execution is required before checking the condition. Keep the condition readable, update loop state inside the body, and make exit paths obvious. For menus and prompts, normalize input with trimming or case-insensitive comparisons so user input behaves predictably.