C# While Loop
The while
loop in C# allows you to repeatedly execute a block of code as long as a certain condition is true. The syntax for a while
loop is as follows:
while (condition)
{
// code to execute as long as condition is true
}
For example, consider the following code snippet:
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
}
In this example, the code inside the while
loop will be executed 10 times, with the value of i
being printed to the console each time. On the first iteration, i
is 0, so the condition i < 10
is true and the code inside the loop is executed. On the second iteration, i
is incremented to 1, and the condition is still true, so the code inside the loop is executed again. This process continues until i
is incremented to 10, at which point the condition i < 10
is false and the loop is exited.
do-while
Loop
C# also provides a do-while
loop, which is similar to a while
loop, but the code inside the loop is always executed at least once. The syntax for a do-while
loop is as follows:
do
{
// code to execute at least once
}
while (condition);
For example, consider the following code snippet:
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 10);