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?

    LoopBest ForRuns at Least Once?
    forKnown number of iterations, countingNo (if condition is false)
    whileDynamic condition, unknown iterationsNo (if condition is false)
    do-whileMust run once, then check conditionYes, always
    foreachIterating arrays, lists, collectionsNo (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.

    Try it Yourself ยป
    C#
    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.

    Try it Yourself ยป
    C#
    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.

    Try it Yourself ยป
    C#
    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's ToList() 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 = ...) scopes i to 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

    • โœ… for loops: for (init; condition; increment) โ€” best for counted iterations
    • โœ… while loops: check condition first, may never run
    • โœ… do-while loops: run body first, then check โ€” always executes at least once
    • โœ… foreach: cleanest way to iterate arrays, lists, and collections
    • โœ… break exits the loop immediately; continue skips 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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service