Bazı işler kaç kez tekrarlanacağı baştan belli olmadan yapılır. Mesela bir oyunda canın sıfıra düşene kadar devam edersin.
İşte böyle durumlarda while kullanılır. Koşul doğru kaldığı sürece döngü çalışmaya devam eder.
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 genelde kaç kez çalışacağı belli olan tekrarlar için uygundur. while ise daha çok koşula bağlı tekrarlar için kullanılır.
Yani sayı odaklı tekrar varsa for, durum odaklı tekrar varsa while daha doğal gelir.
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.
While döngüsünde her tur başlamadan önce koşul tekrar kontrol edilir. Koşul yanlış olursa döngü durur.
Bu yüzden koşulu etkileyen değişkenin döngü içinde güncellenmesi çok önemlidir.
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++;
}
Yeni başlayanların en sık yaptığı hatalardan biri, sayaç ya da koşulu güncellemeyi unutmaktır.
Böyle olunca döngü hiç bitmez. Buna sonsuz döngü denir ve programı kilitleyebilir.
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);
}
While döngüsü çok kullanışlıdır ama en güvenli şekilde yazılması gerekir. Küçük bir kontrol hatası bile tüm akışı bozabilir.
A while loop is very useful, but it should be written carefully. Even a small control mistake can break the entire flow.