Do-While Loop C# Language
C# is a powerful and versatile programming language that provides various control flow structures to manipul
ate the flow of your code. One such structure is the “do-while” loop, which is a fundamental tool for repetitive operations. In this post, we will delve into the do-while loop in C#, discussing its syntax, usage, and providing examples to help you grasp its functionality.The Syntax of the Do-While Loop:
The do-while loop in C# is similar to the while loop, with one key difference: the condition is evaluated after the loop body is executed. This means that the loop body will execute at least once, even if the condition is initially false. The basic syntax of the do-while loop is as follows:
do
{
// Loop body
} while (condition);
Here, the loop body is enclosed within the “do” block, and the condition is checked after the loop body is executed. If the condition is true, the loop will repeat; otherwise, it will terminate.
Example 1: Using a Do-While Loop to Print Numbers
Let’s consider a simple example where we use a do-while loop to print numbers from 1 to 5:
int num = 1;
do
{
Console.WriteLine(num);
num++;
} while (num <= 5);
In this example, the loop body prints the value of the num
variable and increments it by 1. The condition checks if num
is less than or equal to 5. Since the condition is evaluated after the loop body, the numbers 1 through 5 will be printed.
Example 2: Validating User Input
Do-while loops are particularly useful for situations where you want to ensure that a user provides valid input. For instance, you can use a do-while loop to prompt the user for a positive integer:
int userInput;
do
{
Console.Write("Enter a positive integer: ");
} while (!int.TryParse(Console.ReadLine(), out userInput) || userInput <= 0);
Console.WriteLine($"You entered a valid positive integer: {userInput}");
In this example, the loop will keep asking the user for input until a valid positive integer is provided. It checks if the input can be parsed into an integer and if the integer is greater than 0.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.