Loops
Lesson 5 โข Beginner Track
What You'll Learn
- Use for loops when you know the exact number of iterations
- Apply while loops when the stopping condition is dynamic
- Understand do-while loops that always execute at least once
- Iterate arrays and collections cleanly with foreach
- Control loop flow with break (exit early) and continue (skip iteration)
- Build practical patterns: countdowns, search, filtering, and accumulation
๐ก Real-World Analogy
A for loop is like a factory assembly line with a counter โ "do this exactly 100 times." A while loop is like filling a bathtub โ "keep the tap running while the water is below the line." A do-while is like checking your post โ you always check at least once, then continue checking while there are more letters. A foreach is like a teacher doing roll call โ go through each student on the list, one by one.
๐ Which Loop Should I Use?
| Loop | Best For | Runs at Least Once? |
|---|---|---|
| for | Known number of iterations, counting | No (if condition is false) |
| while | Dynamic condition, unknown iterations | No (if condition is false) |
| do-while | Must run once, then check condition | Yes, always |
| foreach | Iterating arrays, lists, collections | No (if collection is empty) |
1. For Loops
The for loop has three parts: initialisation (runs once), condition (checked before each iteration), and increment (runs after each iteration). Perfect for counting, patterns, and known repetition counts.
For Loops
Count up, count down, skip by 2, and build a times table.
using System;
class Program
{
static void Main()
{
// Basic for loop โ count 1 to 5
Console.WriteLine("=== Counting Up ===");
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Count: {i}");
}
// Countdown
Console.WriteLine("\n=== Countdown ===");
for (int i = 5; i >= 1; i--)
{
Console.Write($"{i}... ");
}
Console.WriteLine("Liftoff! ๐");
// Skip by 2 (even numbers)
...2. While & Do-While Loops
while checks the condition before running โ it might never execute. do-while runs the body first, then checks โ guaranteeing at least one execution. Use while for dynamic conditions and do-while for menu systems or input validation.
While & Do-While
Halve a number repeatedly and build a menu system.
using System;
class Program
{
static void Main()
{
// While loop โ unknown iterations
Console.WriteLine("=== Halving Until < 1 ===");
double value = 100;
int steps = 0;
while (value >= 1)
{
Console.WriteLine($"Step {steps}: {value}");
value /= 2;
steps++;
}
Console.WriteLine($"Took {steps} steps to go below 1");
// Do-while โ always runs at least once
Console.WriteLine("\
...3. Foreach, Break & Continue
foreach iterates every element in a collection without needing an index. break exits the loop immediately (useful for search). continue skips the current iteration and moves to the next (useful for filtering).
Foreach, Break & Continue
Iterate collections, search for values, and filter data.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Foreach โ iterate collections
string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
Console.WriteLine("=== Shopping List ===");
foreach (string fruit in fruits)
{
Console.WriteLine($" ๐ {fruit}");
}
// Break โ exit loop early
Console.WriteLine("\n=== Find First Even ===");
int[] numbers = { 7, 3,
...Pro Tips
- ๐ก Prefer foreach over for when iterating collections: It's cleaner and avoids off-by-one index errors.
- ๐ก Use LINQ instead of loops for filtering:
numbers.Where(n => n > 5)is often cleaner than a loop with continue. - ๐ก Avoid modifying a collection inside foreach: This throws
InvalidOperationException. Use a for loop or LINQ'sToList()if you need to remove items. - ๐ก Label your break targets in nested loops: If you only need to exit the inner loop, break only exits the innermost loop by default.
Common Mistakes
- Infinite loops: Forgetting to increment the counter or update the condition variable causes the program to hang forever. Always ensure the loop condition will eventually become false.
- Off-by-one errors:
for (int i = 0; i <= 5; i++)runs 6 times (0-5), not 5. Decide whether to use<or<=carefully. - Using foreach to modify elements: The iteration variable in foreach is read-only.
foreach (var item in list) item = "new";won't work. - Declaring loop variable outside unnecessarily:
for (int i = ...)scopesito the loop. Don't declare it outside unless you need it after the loop ends. - Nested loop performance: A nested loop with 1000 ร 1000 = 1 million iterations. Be careful with large collections.
๐ Lesson Complete
- โ
forloops:for (init; condition; increment)โ best for counted iterations - โ
whileloops: check condition first, may never run - โ
do-whileloops: run body first, then check โ always executes at least once - โ
foreach: cleanest way to iterate arrays, lists, and collections - โ
breakexits the loop immediately;continueskips to the next iteration - โ Watch for infinite loops, off-by-one errors, and nested loop performance
- โ Next lesson: Methods โ organise code into reusable functions
Sign up for free to track which lessons you've completed and get learning reminders.