Limited Offer
60% OFF on all plans!

Loops in C#

Iterate with for, while, do-while, foreach, break, continue, and use LINQ-style iteration on collections.

for Loop

1. How a for Loop Works Internally

The `for` loop has three parts: initializer, condition, and iterator — all on one line.

2. Traversing an Array using for

Use the index to access each element of an array.

3. Nested for Loops

A loop inside a loop — the inner loop runs fully for each step of the outer loop.

while Loop

1. How while Loop Works

The `while` loop checks the condition before each iteration.

2. while with Unknown Iterations

Keep looping until a runtime condition is met.

do-while Loop

1. do-while Execution

Executes the body first, then checks the condition — guarantees at least one run.

2. do-while vs while

The key difference — `do-while` always runs at least once.

foreach Loop

1. foreach with Arrays

`foreach` iterates without needing an index — cleaner than `for` for simple traversal.

2. foreach with Collections (List, Dictionary)

Works on `List<T>`, `Dictionary<K,V>`, and any `IEnumerable<T>`.

3. foreach over a String

A string is iterable — `foreach` yields each `char`.

break & continue

1. break

`break` immediately exits the loop.

2. continue

`continue` skips the rest of the current iteration and moves to the next.

3. Breaking Outer Loops (flag pattern)

C# has no labelled `break`. Use a `bool` flag to exit nested loops.

Reverse Loops

1. Reverse for Loop

Start at the last index and decrement.

ForEach on Collections

1. List.ForEach() with Lambda

`List<T>.ForEach()` takes an `Action<T>` lambda — functional-style iteration.

2. Dictionary ForEach with Lambda

Use `.ToList().ForEach()` to iterate a Dictionary with a lambda.

Best Practices

1. Loop Selection Guidelines

Pick the loop type that best matches the problem.