09. Loops
A loop repeats a block of code. C# has four: for, foreach, while, and do-while. They can all do the same job; each just reads best in a different situation.
for
Use for when you know how many times to repeat. The header has three parts, separated by semicolons: the initializer (int i = 1), the condition checked before each pass (i <= 5), and the iterator run after each pass (i++).
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Lap {i}");
}
int evens = 0;
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
evens++;
}
Console.WriteLine($"Even numbers from 1 to 10: {evens}");Lap 1 Lap 2 Lap 3 Lap 4 Lap 5 Even numbers from 1 to 10: 5
foreach
foreach walks through every item of a collection: an array, a list, even the characters of a string. No counter, no index, no off-by-one mistakes. This is the loop you will write most often.
string[] fruits = ["apple", "banana", "cherry"];
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
foreach (char c in "C#!")
{
Console.Write($"[{c}]");
}
Console.WriteLine();apple banana cherry [C][#][!]
while and do-while
Use while when you don't know the number of repetitions in advance, only the condition to keep going. It checks the condition before each pass, so the body may run zero times.
do-while checks after each pass, so the body always runs at least once. Notice "Attempt 1" prints even though the condition is false from the start.
int balance = 100;
int months = 0;
while (balance < 200)
{
balance += balance / 10;
months++;
}
Console.WriteLine($"Doubled after {months} months: {balance}");
int attempts = 0;
do
{
attempts++;
Console.WriteLine($"Attempt {attempts}");
} while (attempts < 0);Doubled after 8 months: 212 Attempt 1
break and continue
continue skips the rest of the current pass and jumps to the next one. break exits the loop entirely. Here, multiples of 3 are skipped and the loop stops once i passes 7.
for (int i = 1; i <= 10; i++)
{
if (i % 3 == 0)
continue;
if (i > 7)
break;
Console.Write($"{i} ");
}
Console.WriteLine();1 2 4 5 7
Random numbers
Loops and Random go well together. random.Next(1, 7) returns 1 to 6: the lower bound is included, the upper bound is excluded. Casting a number to char turns it into a letter.
var random = new Random(42);
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"Dice: {random.Next(1, 7)}");
}
var password = "";
for (int i = 0; i < 10; i++)
{
password += (char)('a' + random.Next(0, 26));
}
Console.WriteLine($"Password: {password}");Dice: 5 Dice: 1 Dice: 1 Password: negsnetggn
The seed 42 makes the sequence repeatable, so this page shows the same output as your machine. Use new Random() or Random.Shared for real randomness, and never Random for real passwords or tokens: use System.Security.Cryptography.RandomNumberGenerator.
Which loop?
| Situation | Loop |
|---|---|
| Every item in a collection | foreach |
| Known count, or you need the index | for |
| Repeat until a condition changes | while |
| Same, but run at least once | do-while |
A typical endpoint loops over records to build a response. You will write foreach constantly, and later replace many loops with LINQ (intermediate course, lesson 17).
app.MapGet("/orders/total", () =>
{
decimal total = 0;
foreach (var order in orders)
total += order.Amount;
return Results.Ok(new { total });
});