C sharp - while loop
A while
loop in C# is used to repeatedly execute a block of code as long as a specified condition is true. It checks the condition before each iteration, making it a pre-test loop.
Syntax:
while(condition)
{
// Code to execute while the condition is true
}
-
condition: A Boolean expression. If it evaluates to
true
, the loop continues. -
The loop stops when the condition becomes
false
.
Example:
int i = 0;
while (i < 5)
{
Console.WriteLine("i = " + i);
i++;
}
-
If the condition is
false
initially, the loop body won’t execute at all. -
You must ensure the loop will eventually terminate by updating variables inside the loop. Otherwise, you'll create an infinite loop.
Infinite Loop Example:
while (true)
{
Console.WriteLine("This will run forever unless broken manually.");
}
You can use break
or other conditions inside the loop to exit it when needed.