Lesson 9 of 24
In progress
Loops in C#
Count with for, visit collections with foreach, repeat with while, and avoid modifying a collection while enumerating it.
C# offers four loop forms, and the choice between them is mostly about what the reader needs to know: a count, a collection, or a condition.
What you will learn
- Write
for,foreach,whileanddo-whileloops. - Avoid the collection-modified exception.
- Use
break,continueand labelled exits deliberately.
for
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"{i} squared is {i * i}");
}
Initialise, test, update, separated by semicolons. The loop runs while the test is true, so i <= 5 gives five passes from 1 to 5.
For an array or list, the bound is < collection.Length or < list.Count, not <=. The off-by-one with <= throws IndexOutOfRangeException or ArgumentOutOfRangeException, which at least fails loudly.
Counting down is fine: for (int i = n - 1; i >= 0; i--). Removing items by index requires it, because removing shifts the following elements.
foreach
string[] names = { "Ana", "Ravi", "Meera" };
foreach (string name in names)
{
Console.WriteLine($"Hello, {name}");
}
foreach walks any type implementing IEnumerable<T>, which includes arrays, lists, dictionaries and query results. There is no index and no bound, so there is no off-by-one.
The iteration variable is read-only: assigning to it does not compile. For an array of structs that also means you cannot mutate the element through it; use a for loop with an index for that.
Modifying a collection while enumerating
var names = new List<string> { "Ana", "", "Ravi" };
// throws InvalidOperationException
// foreach (var name in names)
// {
// if (name.Length == 0) names.Remove(name);
// }
names.RemoveAll(name => name.Length == 0);
The enumerator detects that the collection changed and throws InvalidOperationException: Collection was modified. RemoveAll is the right tool: one pass, no enumerator invalidation.
For more complex logic, iterate backwards by index or collect the items to remove and delete them after the loop.
while and do-while
int n = 5;
while (n > 0)
{
Console.WriteLine(n);
n--;
}
The condition is checked before each pass, so a false start means no iterations.
string? answer;
do
{
Console.Write("Continue? (yes/no) ");
answer = Console.ReadLine()?.Trim().ToLowerInvariant();
} while (answer is not ("yes" or "no"));
do-while runs the body once before testing, which suits a prompt that must appear at least once. The ?. and is not pattern handle null input in one expression.
A while (true) loop with an explicit break states that the exit is inside the body, which is honest for a menu or a service loop:
while (true)
{
string? line = Console.ReadLine();
if (line is null) break;
Console.WriteLine(line.ToUpperInvariant());
}
break and continue
foreach (int score in new[] { 55, 62, 91, 78 })
{
if (score < 60) continue;
Console.WriteLine(score);
if (score > 90) break;
}
continue skips to the next iteration; break leaves the loop. Both are fine in moderation; a loop with several scattered exits is harder to reason about than one with a clear condition.
break only leaves the innermost loop. To exit nested loops, use a flag, a return from a method, or goto (rarely worth it). Returning from a method is usually the cleanest:
static (int, int)? FindPair(int[,] grid, int target)
{
for (int i = 0; i < grid.GetLength(0); i++)
for (int j = 0; j < grid.GetLength(1); j++)
if (grid[i, j] == target) return (i, j);
return null;
}
A nullable tuple return says "found or not" in the type, and the nested loops exit in one statement.
Loop cost
A loop inside a loop runs the inner body n × m times. Two lists of ten thousand become a hundred million comparisons, which is the shape behind many slow pages and reports.
The usual fix is a dictionary built in one pass:
var priceById = products.ToDictionary(p => p.Id, p => p.Price);
Then the second loop is a lookup instead of a search. That single change turns quadratic work into linear work, and it is worth looking for whenever two nested loops walk the same collections.
Choosing a form
- A known count or an index:
for. - Every element of a collection:
foreach. - A condition unrelated to a count:
while. - At least one pass:
do-while.
Using foreach where it fits tells the reader the index is irrelevant, which is information the for version does not give.
Removing items from a list inside foreach. The enumerator throws, or in older code the loop silently skips elements. Use RemoveAll or iterate backwards.
Print a multiplication table from 1 to 5, then find the first pair whose product exceeds 12 using a method that returns a nullable tuple.
Show solution
static (int a, int b)? FirstAbove(int limit) { for (int i = 1; i <= 5; i++) for (int j = 1; j <= 5; j++) if (i * j > limit) return (i, j); return null; } for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) Console.Write($"{i * j,3}"); Console.WriteLine(); } var found = FirstAbove(12); Console.WriteLine(found is null ? "none" : $"{found.Value.a} x {found.Value.b}"); The method returns as soon as it finds a pair, so the nested loops exit together. The nullable tuple makes "not found" explicit, and the caller handles both cases without a sentinel value.
Recap
forfor counts and indexes,foreachfor collections,whilefor conditions.- Do not modify a collection while enumerating it; use
RemoveAllor index backwards. - Nested loops multiply cost; a dictionary lookup usually replaces the inner loop.
Next, arrays and the span type that lets you work with slices without copying.
Can foreach iterate a dictionary?
Is foreach slower than for?
Progress is saved in this browser only. No account, no email.