Loops

Reviewed & published by Brayan K

By the end of this lesson you'll be able to repeat work without copy-pasting it — counting with for, looping until a condition changes with while, walking through arrays with foreach, and steering the flow with break and continue.

Part of the free C# course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

What You'll Learn

💡 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. Loops exist so you never copy-paste the same line a hundred times: you describe the work once and let the computer repeat it.

📊 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 in its header: initialisation (runs once at the start), condition (checked before every iteration — the loop keeps going while it's true), and step (runs after each iteration, usually i++). It's the natural choice when you know how many times you want to repeat, or you're counting through numbers. Read the worked example first, run it, then you'll finish one yourself.

using System;

class Program
{
    static void Main()
    {
        // A for loop has THREE parts in its header:
        //   for (start ; condition ; step)
        //   |-------|  |--------|  |----|
        //   runs once  checked     runs after
        //              every loop  every loop

        // Count 1 to 5
        Console.WriteLine("=== Counting Up ===");
        for (int i = 1; i <= 5; i++)        // i goes 1,2,3,4,5 then stops
        {
            Console.WriteLine($"Count: {i}"); // Count: 1 ... Count: 5
        }

        // Countdown — start high, step DOWN with i--
        Console.WriteLine("\n=== Countdown ===");
        for (int i = 5; i >= 1; i--)
        {
            Console.Write($"{i}... ");       // 5... 4... 3... 2... 1...
        }
        Console.WriteLine("Liftoff! 🚀");

        // Skip by 2 with i += 2 — only even numbers
        Console.WriteLine("\n=== Even Numbers 1-10 ===");
        for (int i = 2; i <= 10; i += 2)
        {
            Console.Write($"{i} ");          // 2 4 6 8 10
        }

        // Build a times table by multiplying i each loop
        Console.WriteLine("\n\n=== 5x Table ===");
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"5 x {i} = {5 * i}"); // 5 x 1 = 5 ... 5 x 5 = 25
        }
    }
}

// ✅ Expected output:
//    === Counting Up ===
//    Count: 1
//    Count: 2
//    Count: 3
//    Count: 4
//    Count: 5
//
//    === Countdown ===
//    5... 4... 3... 2... 1... Liftoff! 🚀
//
//    === Even Numbers 1-10 ===
//    2 4 6 8 10
//
//    === 5x Table ===
//    5 x 1 = 5
//    5 x 2 = 10
//    5 x 3 = 15
//    5 x 4 = 20
//    5 x 5 = 25

Your turn. The loop below is meant to add up 1 + 2 + 3 + 4 + 5, but the header is blank. Fill in the three ___ blanks using the hints, then run it.

using System;

class Program
{
    static void Main()
    {
        // 🎯 YOUR TURN — fill in the blanks marked with ___ then run it.
        // Goal: add up every number from 1 to 5 (1+2+3+4+5).

        int total = 0;             // the running total starts at zero

        // 1) Start the counter at 1
        // 2) Keep looping while i is 5 or less  (use <=)
        // 3) Add 1 to i after each loop  (use i++)
        for (int i = ___; i ___ 5; ___)   // 👉 fill: start=1, condition=i <= 5, step=i++
        {
            total += i;            // add the current number onto the total
        }

        Console.WriteLine($"The total is {total}");

        // ✅ Expected output:
        //    The total is 15
    }
}

2. While & Do-While Loops

while checks the condition before running the body — so if the condition starts false, the body never runs at all. do-while runs the body first and checks afterwards, which guarantees at least one run. Use while when you don't know how many iterations you'll need (keep going while something is true), and do-while for menus or input that must show at least once.

using System;

class Program
{
    static void Main()
    {
        // while — you DON'T know how many loops you'll need.
        // It checks the condition BEFORE the body runs.
        Console.WriteLine("=== Halving Until < 1 ===");
        double value = 100;
        int steps = 0;
        while (value >= 1)             // stop as soon as value drops below 1
        {
            Console.WriteLine($"Step {steps}: {value}"); // 100, 50, 25, 12.5...
            value /= 2;                // <-- the line that moves us toward the end
            steps++;
        }
        Console.WriteLine($"Took {steps} steps to go below 1"); // Took 7 steps...

        // do-while — runs the body FIRST, then checks. Always runs >= 1 time.
        Console.WriteLine("\n=== Menu System ===");
        int choice;
        do
        {
            Console.WriteLine("1. Play Game");
            Console.WriteLine("2. View Score");
            Console.WriteLine("3. Exit");
            choice = 3;                // pretend the user picked Exit
            Console.WriteLine($"You selected: {choice}"); // You selected: 3
        } while (choice != 3);         // condition is false, so we leave the loop
        Console.WriteLine("Goodbye! 👋");
    }
}

// ✅ Expected output:
//    === Halving Until < 1 ===
//    Step 0: 100
//    Step 1: 50
//    Step 2: 25
//    Step 3: 12.5
//    Step 4: 6.25
//    Step 5: 3.125
//    Step 6: 1.5625
//    Took 7 steps to go below 1
//
//    === Menu System ===
//    1. Play Game
//    2. View Score
//    3. Exit
//    You selected: 3
//    Goodbye! 👋

3. Foreach, Break & Continue

foreach visits every element in a collection without you managing an index — cleaner and safer than a for loop for arrays and lists. break exits the loop immediately (perfect for "stop once I've found it"). continue skips just the current item and moves to the next (perfect for "ignore the bad ones and keep going").

using System;

class Program
{
    static void Main()
    {
        // foreach — visit EVERY item in a collection, no index needed.
        string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
        Console.WriteLine("=== Shopping List ===");
        foreach (string fruit in fruits)
        {
            Console.WriteLine($"  🍎 {fruit}");   // one line per fruit
        }

        // break — stop the loop the moment you've found what you need.
        Console.WriteLine("\n=== Find First Even ===");
        int[] numbers = { 7, 3, 9, 4, 11, 2 };
        foreach (int num in numbers)
        {
            Console.Write($"Checking {num}... ");
            if (num % 2 == 0)                      // % is the remainder; even => 0
            {
                Console.WriteLine($"Found it! First even = {num}"); // stops at 4
                break;                             // leave the loop immediately
            }
            Console.WriteLine("odd, skipping");
        }

        // continue — skip THIS item and jump to the next one.
        Console.WriteLine("\n=== Skip Negatives ===");
        int[] scores = { 85, -1, 92, -3, 78, 95 };
        int total = 0, count = 0;
        foreach (int s in scores)
        {
            if (s < 0) continue;                   // ignore the -1 and -3
            total += s;
            count++;
        }
        Console.WriteLine($"Average of valid scores: {total / count}"); // 350/4 = 87
    }
}

// ✅ Expected output:
//    === Shopping List ===
//      🍎 Apple
//      🍎 Banana
//      🍎 Cherry
//      🍎 Date
//      🍎 Elderberry
//
//    === Find First Even ===
//    Checking 7... odd, skipping
//    Checking 3... odd, skipping
//    Checking 9... odd, skipping
//    Checking 4... Found it! First even = 4
//
//    === Skip Negatives ===
//    Average of valid scores: 87

Now you try. The loop below should total only the positive numbers and skip the negatives. Fill in the two ___ blanks:

using System;

class Program
{
    static void Main()
    {
        // 🎯 YOUR TURN — fill in the blanks marked with ___ then run it.
        // Goal: total ONLY the positive numbers, skipping every negative.

        int[] readings = { 10, -5, 20, -2, 30 };
        int total = 0;

        // 1) Loop over EVERY value in readings
        foreach (int n in ___)         // 👉 the array to walk through: readings
        {
            // 2) If n is negative, skip it and go to the next one
            if (n < 0) ___;            // 👉 the keyword that skips one iteration: continue

            total += n;                // only positive numbers reach this line
        }

        Console.WriteLine($"Total of positives = {total}");

        // ✅ Expected output:
        //    Total of positives = 60
    }
}

4. Nested Loops

A nested loop is simply a loop inside another loop. The outer loop runs once per "row"; for each of those passes the inner loop runs all the way through. They're the natural fit for grids, tables, and anything two-dimensional. The key thing to hold in your head: if the outer loop runs 3 times and the inner loop runs 3 times, the inner body runs 3 × 3 = 9 times in total.

using System;

class Program
{
    static void Main()
    {
        // A nested loop is a loop INSIDE another loop.
        // The OUTER loop runs once per row; for each row the
        // INNER loop runs all the way through (all its columns).

        // Print a 3x3 grid of stars
        Console.WriteLine("=== Star Grid ===");
        for (int row = 1; row <= 3; row++)        // outer: 3 rows
        {
            for (int col = 1; col <= 3; col++)    // inner: 3 stars per row
            {
                Console.Write("* ");              // no newline yet
            }
            Console.WriteLine();                  // end the row -> newline
        }
        // Output:
        //   * * *
        //   * * *
        //   * * *

        // Multiplication grid — inner loop uses the outer loop's value
        Console.WriteLine("\n=== Times Tables 1-3 ===");
        for (int a = 1; a <= 3; a++)              // a = 1, then 2, then 3
        {
            for (int b = 1; b <= 3; b++)          // b runs 1..3 for EACH a
            {
                Console.Write($"{a * b}\t");      // 1 2 3 / 2 4 6 / 3 6 9
            }
            Console.WriteLine();
        }
        // The inner loop runs 3 (rows) x 3 (cols) = 9 times in total.
    }
}

// ✅ Expected output:
//    === Star Grid ===
//    * * *
//    * * *
//    * * *
//
//    === Times Tables 1-3 ===
//    1	2	3
//    2	4	6
//    3	6	9

🔎 Deep Dive: break inside a nested loop

A common surprise: break only exits the innermost loop it sits in — the outer loop keeps going. If you need to leave both loops at once, the simplest fix is a boolean flag the outer loop also checks.

bool found = false;
for (int i = 0; i < 3 && !found; i++)   // outer also checks the flag
{
    for (int j = 0; j < 3; j++)
    {
        if (i + j == 3)
        {
            found = true;   // signal the outer loop to stop
            break;          // leaves the INNER loop only
        }
    }
}

Avoid deeply nesting more than two or three levels — it gets hard to read fast. If you find yourself at four levels deep, that's usually a sign to pull the inner work out into a method (the next lesson).

Putting It Together: a Mini Scoreboard

Here's a small program that uses everything from this lesson at once — a for loop to total and average the scores, a foreach to find the highest, and a break to stop at the first distinction. You understand every line now.

using System;

class Program
{
    static void Main()
    {
        // === Mini scoreboard — uses for, foreach, break & accumulation ===
        int[] scores = { 42, 88, 73, 95, 60 };

        // 1) Sum every score with a for loop, then average it.
        int total = 0;
        for (int i = 0; i < scores.Length; i++) // i = 0..4 (Length is 5)
        {
            total += scores[i];                 // scores[0]+...+scores[4]
        }
        Console.WriteLine($"Average: {total / scores.Length}"); // 358/5 = 71

        // 2) Find the highest score with a foreach.
        int highest = scores[0];
        foreach (int s in scores)
        {
            if (s > highest) highest = s;       // remember the biggest so far
        }
        Console.WriteLine($"Top score: {highest}"); // Top score: 95

        // 3) Stop at the first score over 90 with break.
        foreach (int s in scores)
        {
            if (s > 90)
            {
                Console.WriteLine($"First distinction: {s}"); // 95
                break;
            }
        }
    }
}

// ✅ Expected output:
//    Average: 71
//    Top score: 95
//    First distinction: 95

Notice scores.Length — that's how many items the array holds. Using i < scores.Length (not a hard-coded number) means the loop still works if you add or remove scores.

Pro Tips

Common Errors (and the fix)

📋 Quick Reference

TaskCodeResult
Count 1 to 5for (int i = 1; i <= 5; i++)1,2,3,4,5
Count 0 to 4for (int i = 0; i < 5; i++)runs 5 times
Step by 2i += 22,4,6,...
Loop until conditionwhile (x >= 1)may run 0 times
Run at least oncedo { ... } while (cond);always 1+ runs
Walk an arrayforeach (int n in nums)each element
Exit earlybreak;leaves the loop
Skip this onecontinue;next iteration

Frequently Asked Questions

Q: When should I use for vs foreach?

Use foreach when you just want to look at every element of a collection — it's cleaner and can't go out of bounds. Use for when you need the index number itself (e.g. to change list[i]), to count by something other than 1, or to loop backwards.

Q: My program froze and never finishes. What happened?

You almost certainly wrote an infinite loop — the condition never becomes false. Check that something inside the loop changes the variable the condition tests (a missing i++ is the usual culprit).

Q: What's the real difference between break and continue?

break ends the whole loop right away. continue ends only the current iteration and jumps back to the top for the next one. Think "break = quit", "continue = skip".

Q: When do I need do-while instead of while?

Use do-while when the body must run at least once before you can check the condition — classically a menu that shows the options, reads a choice, then loops if the user didn't pick "exit".

Q: In a nested loop, why does break not stop everything?

break only exits the loop it's directly inside — the innermost one. The outer loop carries on. To leave both, set a bool flag, break the inner loop, and have the outer loop's condition check that flag too.

Mini-Challenge: Sum the Even Numbers

No blanks this time — just a brief and an outline to keep you on track. Write a loop that adds up every even number from 1 to 20, then print the total. Run it and check your output against the expected line in the comments.

using System;

class Program
{
    static void Main()
    {
        // 🎯 MINI-CHALLENGE: Sum the even numbers from 1 to 20
        // 1. Make an int "total" set to 0.
        // 2. Loop a counter i from 1 up to and including 20.
        // 3. If i is even (i % 2 == 0), add it to total.
        //    (Or step by 2 from the start — your choice!)
        // 4. Print: "Sum of evens = {total}"
        //
        // ✅ Expected output:
        //    Sum of evens = 110     (that's 2+4+6+...+20)

        // your code here
    }
}

🎉 Lesson Complete

Practice quiz

What are the three parts of a for loop header, in order?

  • condition; step; start
  • step; start; condition
  • start; condition; step
  • start; step; condition

Answer: start; condition; step. A for loop is for (initialisation; condition; step), e.g. for (int i = 1; i <= 5; i++).

Which loop is guaranteed to run its body at least once?

  • do-while
  • for
  • while
  • foreach

Answer: do-while. do-while runs the body first and checks the condition afterwards, so it always runs at least once.

How many times does for (int i = 0; i < 5; i++) run?

  • 4 times
  • 6 times
  • 0 times
  • 5 times

Answer: 5 times. i takes the values 0, 1, 2, 3, 4 — that is 5 iterations.

What does the break keyword do inside a loop?

  • Skips the current iteration
  • Exits the loop immediately
  • Restarts the loop
  • Pauses for a second

Answer: Exits the loop immediately. break leaves the loop entirely the moment it runs.

What does the continue keyword do?

  • Skips the rest of this iteration and moves to the next
  • Exits the loop
  • Ends the program
  • Repeats the current item forever

Answer: Skips the rest of this iteration and moves to the next. continue skips to the next iteration, ignoring the rest of the current loop body.

Which loop is the cleanest way to visit every element of an array?

  • for
  • while
  • foreach
  • do-while

Answer: foreach. foreach walks every element without managing an index, avoiding off-by-one errors.

In a nested loop, what does break in the inner loop exit?

  • Both loops
  • Only the innermost loop
  • The whole program
  • Nothing

Answer: Only the innermost loop. break only leaves the innermost loop it sits in; the outer loop keeps running.

A while loop whose counter is never updated causes what?

  • A compile error
  • It runs exactly once
  • It runs zero times
  • An infinite loop

Answer: An infinite loop. If nothing moves the variable toward the stopping condition, the loop never ends — an infinite loop.

How many times does the inner body run if the outer loop runs 3 times and the inner runs 3 times each?

  • 3
  • 9
  • 6
  • 27

Answer: 9. The inner body runs 3 x 3 = 9 times in total.

What does scores.Length give for an array?

  • The last element
  • The first index
  • The number of elements it holds
  • Always 0

Answer: The number of elements it holds. Length is the count of elements; using i < scores.Length keeps a loop in bounds.

Continue this course