Loops
Learn for, while, do-while, and foreach loops, plus break and continue.
for Loop
Use a `for` loop when you know how many times you want to repeat something, or need direct access to a counter. It combines initialization, a condition, and an increment step into one compact header.
for (int i = 1; i <= 5; i++){ Console.WriteLine($"Count: {i}");}Click Run to see what this code prints.
A for loop's three parts — initialization, condition, increment — are each independently optional and flexible, which is why for loops can express far more than simple counting.
for (int i = 10; i > 0; i -= 2) // counts down by 2{ Console.WriteLine(i);}while Loop
A `while` loop checks its condition before each iteration, including the very first — if the condition is false immediately, the body never runs at all. It is useful when the number of repetitions isn't known in advance.
int count = 0;while (count < 3){ Console.WriteLine($"count is {count}"); count++;}do-while Loop
A `do-while` loop always runs its body at least once, since the condition is checked after the first iteration rather than before — genuinely useful for "keep asking until valid input is given" style prompts.
int input;do{ Console.Write("Enter a positive number: "); input = int.Parse(Console.ReadLine()!);} while (input <= 0);A while loop might run zero times; a do-while loop always runs at least once — that single difference is the entire deciding factor between them.
foreach Loop
`foreach` iterates over each element in a collection without needing to manage an index manually — the most common, safest loop for arrays, lists, and other collections, since it eliminates the classic "off-by-one" indexing bug entirely.
string[] fruits = { "Apple", "Banana", "Cherry" };foreach (string fruit in fruits){ Console.WriteLine(fruit);}Click Run to see what this code prints.
You cannot modify the collection you're iterating over inside a foreach loop (adding or removing elements throws an exception), and you can't reassign the loop variable itself — if you need to modify the collection or track a position, use a for loop with an explicit index instead.
break & continue
break exits the entire loop immediately, skipping any remaining iterations. continue skips just the rest of the current iteration and moves on to the next one, without exiting the loop.
for (int i = 1; i <= 10; i++){ if (i == 5) break; // exits the loop entirely if (i % 2 == 0) continue; // skips to the next iteration Console.WriteLine(i);}Click Run to see what this code prints.
Nested Loops
Loops can nest inside one another — the inner loop completes all of its iterations for each single iteration of the outer loop. A classic example is printing a multiplication table.
for (int row = 1; row <= 3; row++){ for (int col = 1; col <= 3; col++) { Console.Write($"{row * col}\t"); } Console.WriteLine(); // new line after each row}Click Run to see what this code prints.
A plain break inside a nested loop only exits the innermost loop it's directly inside of — to exit an outer loop from deep within a nested structure, C# offers a labeled break (rarely used) or, far more commonly, extracting the nested loops into their own method and using return instead.
Infinite Loops (and Avoiding Them by Accident)
A loop whose condition never becomes false runs forever, freezing your program (or, for a console app, requiring you to force-quit it). While(true) loops are sometimes intentional — for a server that runs until manually stopped — but an accidental infinite loop is one of the most common beginner bugs.
// ❌ Accidental infinite loop — i is never incremented!int i = 0;while (i < 5){ Console.WriteLine(i); // forgot: i++;}Before running any while or for loop, double-check that whatever the condition depends on is genuinely updated somewhere inside the loop body — this single check prevents the majority of accidental infinite loops.
Classic Practice Example: FizzBuzz
FizzBuzz is a famous, deceptively simple programming exercise (often used in coding interviews) that combines a loop, conditionals, and the modulus operator: print numbers 1 to 100, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
for (int i = 1; i <= 15; i++){ if (i % 15 == 0) Console.WriteLine("FizzBuzz"); else if (i % 3 == 0) Console.WriteLine("Fizz"); else if (i % 5 == 0) Console.WriteLine("Buzz"); else Console.WriteLine(i);}Click Run to see what this code prints.
Choosing the Right Loop
| Situation | Best Loop |
|---|---|
| You know exactly how many times to repeat | for |
| You're iterating over every item in a collection | foreach |
| The repeat count depends on a condition checked before starting | while |
| The body must run at least once no matter what | do-while |
Common Beginner Mistakes
Always verify the condition's dependency is genuinely modified somewhere inside the loop body.
Adding or removing items from a collection while foreach-iterating over it throws an InvalidOperationException — use a for loop with an index, or iterate over a copy, instead.
for (int i = 0; i <= array.Length; i++) runs one iteration too many, causing an out-of-range error — remember array indices go from 0 to Length - 1, so the condition should be i < array.Length.
FAQs
Use `foreach` for collections whenever you don't need the index or aren't modifying the collection, `for` when you need precise control over a counter, and `while`/`do-while` for condition-driven repetition where the count isn't known upfront.
Yes — for (;;) { } runs forever unless broken out of explicitly with break, functionally identical to while (true) { }; both forms appear in real code, though while (true) is generally considered more readable.
Just the innermost loop it's directly written inside of — exiting multiple nested loops at once requires a labeled break, a flag variable, or refactoring the loops into their own method.
Key Takeaways
- for loops when the repeat count is known or you need an explicit counter.
- while checks before running (may run zero times); do-while checks after (always runs at least once).
- foreach is the cleanest, safest way to iterate over a collection, but can't modify the collection or reassign its loop variable.
- break exits a loop entirely; continue skips just the current iteration.
- Always double-check that a while/for loop's condition dependency is actually updated inside the loop, to avoid accidental infinite loops.
Summary
Loops — for, while, do-while, and foreach — are how every C# program repeats work, and FizzBuzz is a genuinely useful way to cement how loops, conditionals, and the modulus operator combine in practice. Next, you'll learn arrays, the fundamental way to store multiple values together.