While in c# example for loop

While in c# example for loop


Understanding While Loops in C# with Examples

In C#, the while loop is a fundamental control flow statement used to execute a block of code repeatedly based on a given condition. Let's dive into how while loops work, along with practical examples:

The Basics of While Loops:

The syntax of a while loop in C# is straightforward:

while (condition)
{
    // Code to be executed repeatedly
}

The loop continues to execute the code block as long as the specified condition evaluates to true. If the condition becomes false, the loop terminates, and the program continues with the next line of code after the loop.

Example: Using While Loop for Iteration:

Suppose we want to print numbers from 1 to 5 using a while loop:

int i = 1;
while (i <= 5)
{
    Console.WriteLine(i);
    i++;
}

In this example, the loop iterates from 1 to 5, printing each number on a separate line.

Breaking Out of a While Loop:

Sometimes, you may need to exit a while loop prematurely based on a certain condition. This is where the break statement comes in handy:

int i = 1;
while (true)
{
    Console.WriteLine(i);
    if (i == 5)
    {
        break; // Exit the loop when i equals 5
    }
    i++;
}

The break statement terminates the loop immediately when the value of i becomes 5.

The While-Else Construct:

In C#, there is no direct else clause for a while loop. However, you can achieve similar behavior using a flag variable:

int i = 1;
bool flag = false;
while (i <= 5)
{
    Console.WriteLine(i);
    if (i == 3)
    {
        flag = true;
    }
    i++;
}

if (!flag)
{
    Console.WriteLine("Loop completed without encountering i equals 3.");
}

In this example, if the loop completes without encountering i equals 3, the message "Loop completed without encountering i equals 3." is displayed.

By mastering the concepts and examples provided above, you'll be well-equipped to use while loops effectively in your C# programs. Stay tuned for more insights and examples on C# control flow statements!

Leave a reply Your email address will not be published. Required fields are marked*