Light Mode Image

C# Do While Loop

The do-while loop is used to repeatedly execute a block of statements while a specified condition is true.

 

The key difference between a while loop and a do-while loop is that the do-while loop guarantees that the block of code is executed at least once, as the condition is checked after the execution of the block.

 

Syntax of a do-while loop in C#.

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

 

Example of a do-while loop in C#.

using System;

class Program
{
    static void Main()
    {
        int counter = 1;

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

 

In this example, the loop will execute the block of code inside the do statement, printing the value of counter and incrementing it, until the condition counter <= 5 becomes false.

 

It's important to ensure that the loop condition will eventually become false. Otherwise, the loop will continue indefinitely, resulting in an infinite loop.

 

Always make sure that the loop condition is properly defined and updated within the loop block.