C# While Loop
Introduction to While Loop
A while loop in C# repeats a block of code as long as a given condition is true.
It is useful when the number of iterations is not known in advance.
Syntax of While Loop
The condition is checked before each iteration.
If the condition evaluates to false initially, the loop body will not run at all.
Example
using System;
namespace WhileLoopExample
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 5)
{
Console.WriteLine($"i = {i}");
i++;
}
}
}
}
Output
i = 0 i = 1 i = 2 i = 3 i = 4
Infinite While Loop
If the condition in a while loop never becomes false, the loop will run infinitely.
Be careful to include logic that eventually ends the loop.
Example
using System;
namespace InfiniteWhile
{
class Program
{
static void Main(string[] args)
{
int count = 0;
while (true)
{
Console.WriteLine($"Count = {count}");
count++;
if (count >= 3)
{
break;
}
}
}
}
}
Output
Count = 0 Count = 1 Count = 2