Home About Lessons Blog On The Mic Contact Projects
Lessons BASIC · C#

C# Basics — While Loop

7 min read · Emre Ulutabak
1
What is while?

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.

csharp
int enerji = 3;

while (enerji > 0)
{
    Console.WriteLine("Devam ediyorsun...");
    enerji--;
}
💡
While works with the idea of 'keep going as long as the condition is true'.
2
Difference from for

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.

3
Condition logic

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.

csharp
int sayac = 1;

while (sayac <= 5)
{
    Console.WriteLine(sayac);
    sayac++;
}
💡
If nothing changes the condition, a while loop can continue forever.
4
Risk of infinite loop

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.

csharp
int i = 1;

while (i <= 5)
{
    Console.WriteLine(i);
}
💡
In the example above, i never changes, so the loop never ends.
5
Golden rules

A while loop is very useful, but it should be written carefully. Even a small control mistake can break the entire flow.

💡
Think about the condition and the line that changes it together. If one exists, the other should too.
💡
If the number of repetitions is known, using for instead of while may be cleaner.
💡
Always keep the possibility of an infinite loop in mind.
MINI QUIZ
Which of the following is correct?
A while loop runs while the condition is false
A while loop runs as long as the condition stays true
Variables cannot be updated inside while
While is only used with strings