In the world of programming, loops are essential for executing a block of code repeatedly. C# provides several types of loops, each serving different purposes based on specific requirements. One such loop is the do-while loop.
A do-while loop is unique because it guarantees that its body will execute at least once. This behavior sets it apart from other looping constructs like for and while, which might not execute their bodies if the condition is initially false.
The basic syntax of a do-while loop in C# is as follows:
do
{
// Code to be executed
} while (condition);
Here's how it works:
do braces executes first.while statement is evaluated.true, the loop repeats from step 1. If it evaluates to false, the loop terminates.This ensures that the loop body will execute at least once before the condition is checked.
Let's explore some practical examples to understand how do-while loops work in C#.
In this example, we'll print numbers from 1 to 5 using a do-while loop.
int number = 1;
do
{
Console.WriteLine(number);
number++;
} while (number <= 5);
Output:
1 2 3 4 5
Do-while loops can also be used to create infinite loops, which can be controlled using the break statement.
int count = 0;
do
{
Console.WriteLine("This is an infinite loop.");
count++;
if (count == 3)
{
break; // Exit the loop after 3 iterations
}
} while (true);
Output:
This is an infinite loop. This is an infinite loop. This is an infinite loop.
Do-while loops are particularly useful for validating user input. Here, we'll keep asking the user to enter a positive number until they provide one.
int userInput;
do
{
Console.Write("Enter a positive number: ");
userInput = int.Parse(Console.ReadLine());
} while (userInput <= 0);
Console.WriteLine($"You entered {userInput}, which is a positive number.");
Output Example:
Enter a positive number: -5 Enter a positive number: 0 Enter a positive number: 7 You entered 7, which is a positive number.
In the next section, we'll explore how to control loops using break and continue statements. These statements allow you to exit a loop prematurely or skip certain iterations, providing more flexibility in your code.
Stay tuned for more tutorials on C# control flow!