C# > Core C# > Control Flow > do-while Loop

Simple do-while Loop Example

This snippet demonstrates the basic usage of a do-while loop in C#. The loop executes a block of code at least once and then continues to iterate as long as a specified condition is true.

Code Snippet

This code initializes a counter variable to 0. The do-while loop then executes the code within its block, which prints the current value of the counter and increments it. This process repeats as long as the counter is less than 5. Crucially, the code inside the loop *always* executes at least once, even if the condition (counter < 5) is initially false.

using System;

public class DoWhileExample
{
    public static void Main(string[] args)
    {
        int counter = 0;

        do
        {
            Console.WriteLine("Counter: " + counter);
            counter++;
        } while (counter < 5);

        Console.WriteLine("Loop finished.");
    }
}

Concepts Behind the Snippet

The do-while loop is a control flow statement that executes a block of code at least once and then repeatedly executes the block as long as a specified boolean condition is true. The condition is evaluated *after* each iteration of the loop. This contrasts with the `while` loop, where the condition is checked *before* each iteration. Because of this, `do-while` loops are suited for scenarios that require a block of code to run at least once.

Real-Life Use Case

A common use case for a do-while loop is prompting a user for input until they provide valid data. For example, you might ask for a number within a specific range and keep prompting them until they enter a valid number. The loop has to execute at least once to prompt the user.

using System;

public class InputValidationExample
{
    public static void Main(string[] args)
    {
        int number;
        bool isValid;

        do
        {
            Console.Write("Enter a number between 1 and 10: ");
            string input = Console.ReadLine();

            isValid = int.TryParse(input, out number) && (number >= 1 && number <= 10);

            if (!isValid)
            {
                Console.WriteLine("Invalid input. Please try again.");
            }

        } while (!isValid);

        Console.WriteLine("You entered: " + number);
    }
}

Best Practices

  • Initialize Variables: Ensure that variables used in the loop's condition are properly initialized before the loop starts.
  • Avoid Infinite Loops: Double-check the loop's condition to prevent infinite loops. Make sure the condition will eventually become false.
  • Clarity: Use meaningful variable names and clear comments to make the code easier to understand.

Interview Tip

Be prepared to explain the difference between `while` and `do-while` loops. The key difference is that `do-while` always executes the code block at least once, while `while` might not execute it at all if the condition is initially false. Also, be ready to give examples of when each type of loop is more appropriate.

When to Use Them

Use a `do-while` loop when you need to ensure that a block of code is executed at least once, regardless of the initial condition. This is useful for scenarios such as menu-driven programs, input validation, and other situations where an initial action is always required.

Alternatives

The primary alternative to a `do-while` loop is a standard `while` loop. You can simulate a `do-while` loop with a `while` loop by executing the code block once before entering the loop. However, `do-while` provides a more concise and readable way to express this pattern.

// do-while equivalent using while
int counter = 0;

// Execute the code block once before the loop
Console.WriteLine("Counter: " + counter);
counter++;

while (counter < 5)
{
    Console.WriteLine("Counter: " + counter);
    counter++;
}

Pros

  • Guaranteed Execution: Ensures that the code block is executed at least once.
  • Readability: Provides a clear and concise way to express the 'execute at least once' pattern.

Cons

  • Less Common: Compared to the `while` loop, `do-while` is used less frequently, which may slightly reduce code readability for some developers.
  • Potential for Redundancy: If not carefully designed, the initial execution of the code block can sometimes lead to redundant operations.

FAQ

  • What happens if the condition in a do-while loop is always true?

    If the condition in a do-while loop is always true, the loop will continue to execute indefinitely, resulting in an infinite loop. This can crash your program or cause it to become unresponsive. Make sure your loop condition eventually becomes false.
  • What is the main difference between a while loop and a do-while loop?

    The key difference is that a do-while loop executes the code block at least once, regardless of the condition. A while loop only executes the code block if the condition is initially true.