Language: EN

csharp-bucle-while

What is and how to use the WHILE and DO-WHILE loop in C#

The while and do-while loops are control structures in C# that allow the execution of a block of code to be repeated while a specific condition is met.

Unlike the for loop, which is used when the exact number of iterations is known, the while and do-while loops are ideal when the number of iterations is unknown (because it depends on an exit condition).

WHILE Loop

The while loop repeats a block of code while a given condition is true. The basic syntax of a while loop in C# is as follows:

while (condition)
{
    // Code to execute while the condition is true
}

The block of code executes repeatedly as long as the specified condition is true. It is important to be careful with the condition to avoid infinite loops.

Let’s see it with an example,

int counter = 0;

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

In this example, the while loop will print the numbers from 0 to 4, as the condition counter < 5 evaluates to true during the first five iterations.

DO-WHILE Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code will execute at least once, even if the condition is false from the start. The basic syntax is as follows:

do
{
    // Code to execute at least once
} while (condition);

The block of code executes first and then checks the condition. If the condition is true, the block executes again; if it is false, the loop ends.

Let’s see it with an example

int counter = 0;

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

This do-while loop will produce the same output as the while loop from the previous example.

Differences between While and Do-While

  • The while loop checks the condition before each iteration, while the do-while loop checks the condition after each iteration.
  • The do-while loop guarantees at least one execution of the block of code, while the while loop may not execute the block if the condition is false from the start.

Practical Examples