while loop in csharp

A while loop in C# repeatedly executes a block of code as long as the specified condition is true. Here's the basic syntax for a while loop in C#:

main.cs
while (condition)
{
    // code to be executed
}
49 chars
5 lines

The condition can be any expression that evaluates to a boolean value (true or false). The loop will continue to execute the code block as long as the condition is true. Once the condition evaluates to false, the loop will exit and the program will continue with the next line of code after the loop.

Here's a simple example of a while loop that counts from 1 to 5:

main.cs
int i = 1;

while (i <= 5)
{
    Console.WriteLine(i);
    i++;
}
66 chars
8 lines

In this example, the condition is i <= 5, which means the loop will execute as long as the value of i is less than or equal to 5. Inside the loop, we print the current value of i and then increment i by 1 using the i++ shorthand for i = i + 1. The output of this code will be:

main.cs
1
2
3
4
5
10 chars
6 lines

gistlibby LogSnag