while Loop (C#)
A while loop in C# repeats a block of code as long as a condition stays true. It is used when you don't know in advance how many times you need to loop.
C#
Make sure something inside the loop eventually makes the condition false, or you create an infinite loop. Use break to exit early and continue to skip to the next iteration.
A related variant, do-while, checks the condition at the end, so the body always runs at least once.
Syntax
while (condition) { ... }Examples
C#
int count = 0;
while (count < 3)
{
Console.WriteLine(count);
count++;
}Output:
0
1
2