Some tasks repeat without knowing the exact number beforehand. For example, in a game you keep going until your health reaches zero.
That is where while is used. The loop keeps running as long as the condition remains true.
int enerji = 3;
while (enerji > 0)
{
Console.WriteLine("Devam ediyorsun...");
enerji--;
}
for is usually better when you know how many times something should repeat. while is better when repetition depends on a condition.
So if the repetition is count-based, use for; if it is state-based, while often feels more natural.
In a while loop, the condition is checked before each round begins. If the condition becomes false, the loop stops.
That is why it is very important to update the variable that affects the condition inside the loop.
int sayac = 1;
while (sayac <= 5)
{
Console.WriteLine(sayac);
sayac++;
}
One of the most common beginner mistakes is forgetting to update the counter or the condition.
When that happens, the loop never ends. This is called an infinite loop and it can freeze the program.
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
}
A while loop is very useful, but it should be written carefully. Even a small control mistake can break the entire flow.