The while loop

The while loop

The while loop in C# is used to repeatedly execute a block of code as long as a specified condition is true. It has the following syntax:

while (condition)

{

    // code to execute

}

The condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop is terminated.

Here’s an example of a while loop that counts from 1 to 10:

int i = 1;

while (i <= 10)

{

    Console.WriteLine(i);

    i++;

}

In this example, the loop starts with the variable i set to 1. The condition statement checks if i is less than or equal to 10. If the condition is true, the loop executes the code inside the loop, which prints the value of i to the console and increments i by 1. The loop continues to execute until the condition is false, which happens after i reaches 11.

You can also use the while loop to implement an infinite loop that continues to execute until it is explicitly terminated, like this:

while (true)

{

    // code to execute

}

In this example, the condition statement is always true, so the loop executes indefinitely until it is terminated by a break statement, a return statement, or some other mechanism. The while loop is a useful construct in C# that allows you to execute a block of code repeatedly while a certain condition is true. By combining while loops with conditional statements and other control flow constructs, you can write programs that can handle a wide range of tasks, from simple data processing to complex algorithms.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Share this post
[social_warfare]
The foreach loop
Creating an Asp Dot Net Website

Get industry recognized certification – Contact us

keyboard_arrow_up