Loops
Loops in C#
C# supports all common loop patterns.
for loop Index-based repetition:
csharp
for (int i = 0; i < 10; i++) { … }foreach loop
Iterates any IEnumerable<T> without managing an index:
csharp
foreach (var item in collection) { … }while loop Condition checked before each iteration:
csharp
while (condition) { … }do-while loop Body runs at least once:
csharp
do { … } while (condition);break and continue
breakexits the nearest loop.continueskips the remaining body and moves to the next iteration.
Key points:
- Prefer
foreachoverforwhen the index is not needed — it works with all collections. - C# foreach uses the iterator pattern internally — never modify the collection inside a foreach.
- LINQ
Where/Selectcan often replace imperative loops for concise transformations.
Code Examples
for, while, do-whilecsharp
using System;
class LoopDemo {
static void Main() {
// for
int sum = 0;
for (int i = 1; i <= 5; i++) sum += i;
Console.WriteLine($"Sum: {sum}");
// while — find first power of 2 >= 100
int n = 1;
while (n < 100) n *= 2;
Console.WriteLine($"First power of 2 >= 100: {n}");
// do-while
int x = 1;
do {
Console.Write(x + " ");
x *= 2;
} while (x <= 8);
Console.WriteLine();
}
}do-while guarantees at least one execution. while may not execute at all if the condition is initially false.
foreach with break and continuecsharp
using System;
class ForeachDemo {
static void Main() {
string[] words = { "apple", "banana", "cherry", "date", "elderberry" };
Console.WriteLine("Words not starting with 'b':");
foreach (var word in words) {
if (word.StartsWith("b")) continue;
Console.WriteLine($" {word}");
}
Console.WriteLine("First word longer than 5 chars:");
foreach (var word in words) {
if (word.Length > 5) {
Console.WriteLine($" {word}");
break;
}
}
}
}continue skips to the next element; break exits the entire loop. foreach works on any IEnumerable<T>.
Quick Quiz
1. Which C# loop is best when you need the index during iteration?
2. What happens if you modify a list inside a foreach loop?
Was this lesson helpful?