C# `do-while` Loops: Implementing At-Least-Once Execution

Learn how to use `do-while` loops in C# to create loops that execute at least one iteration before checking a condition. This tutorial explains the syntax, contrasts `do-while` with `while` loops, and provides examples demonstrating its application in scenarios requiring guaranteed initial execution.



Understanding and Using `do-while` Loops in C#

What is a `do-while` Loop?

The `do-while` loop is a control flow statement in C# that executes a block of code repeatedly *at least once*, and then it checks a condition to determine whether to repeat the loop. It's different from a `while` loop, which checks the condition *before* each iteration. `do-while` is most useful when you need to ensure that the code block is executed at least once, and then the loop may continue based on the result of the condition.

`do-while` Loop Syntax

The syntax is:

Syntax

do {
    // Code to be executed
} while (condition);

The code block within the `do { ... }` section is executed at least once. Then, the `condition` is evaluated; if `true`, the loop repeats; if `false`, the loop terminates.

Example: Printing a Table

This example uses a `do-while` loop to print the numbers 1 through 10 (a simple multiplication table). The loop continues as long as the counter variable `i` is less than or equal to 10.

C# Code

using System;

public class DoWhileExample {
    public static void Main(string[] args) {
        int i = 1;
        do {
            Console.WriteLine(i);
            i++;
        } while (i <= 10);
    }
}

Nested `do-while` Loops

You can nest `do-while` loops (placing one `do-while` loop inside another). The inner loop completes all its iterations for each iteration of the outer loop.

C# Code (Nested do-while)

using System;

public class DoWhileExample {
    public static void Main(string[] args) {
        int i = 1;
        do {
            int j = 1;
            do {
                Console.WriteLine($"{i} {j}");
                j++;
            } while (j <= 3);
            i++;
        } while (i <= 3);
    }
}

Infinite `do-while` Loops

Setting the `while` condition to `true` creates an infinite loop. You would typically use a `break` statement or other mechanism to terminate this type of loop.

C# Code (Infinite do-while)

do {
    Console.WriteLine("This is an infinite loop!");
} while (true); //This will run indefinitely

Conclusion

The `do-while` loop in C# offers a straightforward way to create loops that execute at least once. It's a valuable tool but should be used judiciously to avoid creating difficult-to-debug infinite loops. Always include a mechanism to stop the loop if the condition might never become false.