C# Tutorial: Loops
for, while, do-while, foreach — all the ways to repeat code in C#.
Repeating code
C# has four loop constructs. Use `foreach` for collections, `for` for index-based access, `while` for condition-based looping.
What you'll learn in this C# loops tutorial
This interactive C# tutorial has 8 hands-on exercises. Estimated time: 15 minutes.
- for loop — Classic indexed for loop:
- Count down — Loops can count backwards.
- while loop — `while` loops while a condition is true.
- do-while loop — `do-while` always runs at least once — the condition is checked after.
- foreach loop — `foreach` iterates over any collection.
- break and continue — `break` exits the loop. `continue` skips to the next iteration.
- Nested loops — Loops can be nested. Use descriptive variable names.
- Loop over indices with LINQ range — Use `Enumerable.Range` for index-based loops without a traditional for.
C# Loops concepts covered
- Repeating code