Loops
C# has four ways to repeat a block of code, and they differ mainly in when the condition gets checked and how the counter is managed. Picking the right one is less about correctness — most loops can be rewritten as any of the others — and more about which shape best communicates your intent.
for — when you know the count
A for loop packs the starting value, the continuation condition, and the per-pass update into one line, which makes it the natural choice whenever you're stepping through a known range:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Count: {i}");
}
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
while — when you don't know the count in advance
A while loop checks its condition before every pass and keeps going as long as it's true. It fits situations where the number of iterations depends on something happening during the loop, not on a fixed range you already know:
int ticketsLeft = 3;
while (ticketsLeft > 0)
{
Console.WriteLine($"Selling ticket. {ticketsLeft} left.");
ticketsLeft--;
}
Console.WriteLine("Sold out.");
Selling ticket. 3 left. Selling ticket. 2 left. Selling ticket. 1 left. Sold out.
do-while — when it has to run at least once
A regular while loop can run zero times if its condition is false from the start. do-while checks the condition at the end of the pass instead of the beginning, guaranteeing the body executes at least once — useful for things like "try the login, then keep retrying until it succeeds or we run out of attempts":
int attempts = 0;
int maxAttempts = 3;
bool loginSuccess = false;
do
{
attempts++;
Console.WriteLine($"Attempt {attempts}");
} while (!loginSuccess && attempts < maxAttempts);
Console.WriteLine($"Stopped after {attempts} attempts.");
Attempt 1 Attempt 2 Attempt 3 Stopped after 3 attempts.
break and continue
break exits a loop immediately, skipping every remaining iteration. continue skips only the rest of the current iteration and moves on to the next one:
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue;
}
if (i > 7)
{
break;
}
Console.WriteLine(i);
}
1 3 5 7
Even numbers get skipped by continue before they ever reach the print statement. Once i passes 7, break shuts the whole loop down — which is why 9 never gets a chance to print, even though it's odd.
foreach, is intentionally saved for the next lesson — it's built specifically for walking through arrays and lists, and it makes far more sense once you have a collection to walk through.