C# Keywords Tutorial Part 100: while

C# Keywords Tutorial Part 100: while

C# is a potent programming language that gives developers access to a wide range of constructs to help them accomplish their coding objectives. The “while” loop is one such design element. Developers can continually run a block of code until a certain condition is fulfilled by using the “while” loop. In this blog article, we will examine the C# keyword “while” and offer examples of programs that use it.

Syntax

The syntax of the “while” loop in C# is as follows:

while (condition)
{
    // Code to execute repeatedly
}

The “condition” in the above syntax is a Boolean expression that is evaluated before each iteration of the loop. If the condition evaluates to “true”, the code block is executed. If the condition evaluates to “false”, the loop terminates.

Example 1: Simple while loop

Let’s start with a simple example to illustrate the basic usage of the “while” loop. The following code snippet prints the numbers from 1 to 5 using a while loop.

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

In this example, we initialize a variable “i” to 1 and use it as the loop counter. The condition in the while loop checks if “i” is less than or equal to 5. If the condition is true, the code block inside the loop is executed, which prints the value of “i” and increments it by 1. This process is repeated until the condition becomes false.

Example 2: Using while loop with boolean flag

Sometimes, it’s not possible to determine the number of iterations required in advance. In such cases, we can use a boolean flag to control the loop. The following example shows how to use a while loop with a boolean flag.

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

In this example, we initialize a boolean flag “flag” to true and use it as the loop condition. We also initialize a variable “i” to 0, which acts as the loop counter. The code block inside the loop prints the value of “i” and increments it by 1. If “i” becomes 5, we set the “flag” to false, which terminates the loop.

Example 3: Using while loop to read user input

The “while” loop can also be used to read user input until a specific condition is met. The following example shows how to use a while loop to read user input until the user enters a specific string.

string input = "";
while (input != "quit")
{
    Console.Write("Enter a string (type 'quit' to exit): ");
    input = Console.ReadLine();
    Console.WriteLine("You entered: " + input);
}

In this example, we use a while loop to read user input until the user enters the string “quit”. The code block inside the loop prompts the user to enter a string and reads the input using the Console.ReadLine() method. The loop terminates when the user enters the string “quit”.

Share this post

Leave a Reply

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