Welcome back! On Day 4 your code learned to make decisions. Today we teach it to do things over and over again without you having to copy-paste Console.WriteLine 100 times like some kind of caveman. Enter: loops. π
1. Why Loops Exist
Imagine a teacher tells you: "Write 'I will not talk in class' on the board 50 times." You could write it 50 times by hand. Or you could be clever and say: "Repeat this sentence 50 times." That's exactly what a loop is β a way to tell C#: "Do this block of code, N times, and stop when I say so."
Three flavors in C#: for, while, and foreach. Each has a personality.
2. The for Loop β The Micromanager
Use for when you know exactly how many times you want to repeat something.
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Iteration {i}");
}
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
The header has three parts separated by semicolons:
int i = 0β the initializer. Runs once, at the start.i < 5β the condition. Checked before every iteration. Loop stops when it'sfalse.i++β the updater. Runs at the end of every iteration.
Read it as: "Start with i = 0. While i < 5, run the body. After each run, add 1 to i."
Why does it start at 0? Because programmers count from 0. You'll get used to it. (Eventually.)
3. The while Loop β The Patient One
Use while when you don't know how many iterations you'll need β you just want to keep going as long as some condition is true.
int guess = 0;
while (guess != 7)
{
Console.Write("Guess the number: ");
guess = int.Parse(Console.ReadLine() ?? "0");
}
Console.WriteLine("You got it!");
The loop keeps running until the user types 7. Could take 1 try, could take 400. while doesn't care.
Danger zone: if your condition never becomes false, you've built an infinite loop. Your program will run forever, your fan will spin up, and your laptop will try to become a helicopter. Always make sure something inside the loop eventually changes the condition.
// DON'T DO THIS
while (true)
{
Console.WriteLine("I will never stop");
}
(Well, while (true) does have legitimate uses β but you need a break inside. More on that in a minute.)
4. do...while β The "At Least Once" Loop
A sneaky cousin: do...while runs the body first, then checks the condition. So it's guaranteed to execute at least once.
string input;
do
{
Console.Write("Type 'quit' to exit: ");
input = Console.ReadLine() ?? "";
}
while (input != "quit");
Great for menus and prompts where you always want to ask at least one time.
5. The foreach Loop β The Tour Guide
When you have a collection of things (a list, an array, any IEnumerable), and you want to visit each one, use foreach. It's the cleanest, safest option.
string[] names = ["Alice", "Bob", "Charlie"];
foreach (string name in names)
{
Console.WriteLine($"Hello, {name}!");
}
Read it as: "For each string (call it name) in names, run the body."
No counters, no off-by-one errors, no forgetting to increment i. foreach handles all of that. When in doubt, prefer foreach over for when walking a collection.
We'll meet arrays and collections properly on Day 6 β today just know that foreach is how you politely visit every element.
6. break and continue β The Escape Hatches
Sometimes you need to bail out early or skip an iteration:
breakβ leaves the loop immediately, no questions asked.continueβ skips the rest of the current iteration and jumps to the next one.
for (int i = 0; i < 10; i++)
{
if (i == 3) continue; // skip 3
if (i == 7) break; // stop entirely at 7
Console.WriteLine(i);
}
Output: 0 1 2 4 5 6. Notice 3 is missing (skipped) and 7 onward is gone (broke out).
Use these sparingly. A loop body with five break statements is a cry for help β usually the logic can be rewritten more cleanly.
7. Which Loop Do I Pick?
| Situation | Use |
|---|---|
| You know the exact count (0 to N) | for |
| You loop until something changes | while |
| You want to run the body at least once | do...while |
| You're walking every item in a collection | foreach |
Rule of thumb: start with foreach for collections, for for counting, while for "keep going untilβ¦".
8. Your Homework: FizzBuzz
The classic. Print numbers from 1 to 20. But:
- If the number is divisible by 3, print
"Fizz"instead. - If it's divisible by 5, print
"Buzz"instead. - If it's divisible by both 3 and 5, print
"FizzBuzz". - Otherwise, print the number itself.
for (int i = 1; i <= 20; i++)
{
if (i % 15 == 0)
Console.WriteLine("FizzBuzz");
else if (i % 3 == 0)
Console.WriteLine("Fizz");
else if (i % 5 == 0)
Console.WriteLine("Buzz");
else
Console.WriteLine(i);
}
Remember % (modulo) from Day 3? i % 15 == 0 means "i divides evenly by 15" β which is exactly when it's divisible by both 3 and 5. Check the 15 case first β otherwise 15 would match the % 3 branch and you'd never see "FizzBuzz".
Bonus challenge: rewrite it using a switch expression. (Hint: switch on (i % 3, i % 5) as a tuple.)
For the full loop reference, see the C# iteration statements docs.
Summary of Day 5
forβ known iteration count, classic(init; condition; update)header.whileβ keep going while a condition istrue. Watch out for infinite loops.do...whileβ likewhile, but always runs at least once.foreachβ the cleanest way to walk a collection. No counters, no bugs.breakexits the loop;continueskips to the next iteration.- Rule of thumb:
foreachfor collections,forfor counting,whilefor "until".
Tomorrow: we'll talk about Arrays and Collections β the actual boxes-of-boxes that foreach loves to walk through. Your program is about to graduate from holding one value to holding a whole stack of them. π
See you on Day 6!