Skip to main content

📝 Lesson 3.2: Loops

Computers are brilliant at repetition. Loops let you run the same code many times — 10 times, a million times, or until some condition changes — without copying and pasting a single line.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Repeat code with while and do-while loops
  • Count precisely with a for loop
  • Step through a collection with foreach
  • Control loops with break and continue
  • Recognize and avoid infinite loops

Estimated Time: 45 minutes

Project: Build a countdown, a sum calculator, and a number-guessing loop.

In This Lesson

Why Loops?

Suppose you want to print the numbers 1 through 5. You could write five Console.WriteLine lines — but what about 1 to 1,000? Copying lines doesn't scale. A loop repeats a block of code, so you write it once and let the computer run it as many times as needed.

graph TD A["Enter loop"] --> B{"Condition true?"} B -->|"Yes"| C["Run the loop body"] C --> B B -->|"No"| D["Exit the loop"] style A fill:#eff6ff,stroke:#3b82f6,stroke-width:2px style D fill:#e8f5e9,stroke:#4CAF50,stroke-width:2px

Every loop needs a way to eventually stop. As you'll see, that means changing something each pass so the condition eventually becomes false.

The while Loop

A while loop repeats its block as long as a condition stays true. It checks the condition first, before each pass:

int count = 1;

while (count <= 5)
{
    Console.WriteLine($"Count is {count}");
    count++;   // move toward the stopping point
}

Console.WriteLine("Done!");

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Done!

Notice the three essential parts of any loop:

  1. Start: count begins at 1.
  2. Condition: keep going while (count <= 5).
  3. Update: count++ changes the value each pass so the loop eventually ends.

⚠️ Infinite loops

If the condition never becomes false, the loop runs forever and your program appears to freeze. The usual cause is forgetting the update step — if you delete count++ above, count stays 1 and the loop never stops. If a program hangs, press Ctrl+C in the terminal to stop it, then check that your loop actually changes something each pass.

The do-while Loop

A do-while loop is like while, but it checks the condition at the end. That means the body always runs at least once, even if the condition is false to begin with:

int number;

do
{
    Console.Write("Enter a positive number: ");
    number = int.Parse(Console.ReadLine());
}
while (number <= 0);

Console.WriteLine($"Thank you! You entered {number}.");

This is a perfect fit for input validation: you must ask at least once, and then keep asking until the user cooperates.

💡 while vs. do-while

  • while — checks first; the body may run zero times.
  • do-while — checks last; the body runs at least once.

Note the semicolon after the closing while (...) in a do-while — it's required.

The for Loop

When you know exactly how many times to repeat — or you're counting through a range — the for loop bundles all three loop parts (start, condition, update) neatly onto one line:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"i is {i}");
}

Read the header for (int i = 1; i <= 5; i++) as three parts separated by semicolons:

PartCodeMeaning
Startint i = 1Runs once, before the loop begins.
Conditioni <= 5Checked before each pass; loop continues while true.
Updatei++Runs after each pass.

Output:

i is 1
i is 2
i is 3
i is 4
i is 5

💡 Why i?

The counter is traditionally named i (for "index" or "iterator"). It's one of the few times a single-letter name is considered good style. For nested loops, j and k follow.

for vs. while

They can do the same jobs. Reach for for when you're counting a known number of times; reach for while when you'll loop until some condition changes and you don't know how many passes that will take.

The foreach Loop

A foreach loop steps through every item in a collection — one at a time — without you managing a counter at all. Here it walks through an array of strings (you'll learn arrays fully in Lesson 4.1):

string[] fruits = { "apple", "banana", "cherry" };

foreach (string fruit in fruits)
{
    Console.WriteLine($"I like {fruit}.");
}

Output:

I like apple.
I like banana.
I like cherry.

Read it as: "for each fruit in fruits, do this." On each pass, the variable fruit automatically holds the next item. There's no index to manage and no risk of going out of bounds.

✅ When to use foreach

Use foreach when you want to visit every item in a collection and don't need the position number. If you need the index (or want to skip around), use a for loop instead.

break and continue

Two keywords give you finer control inside any loop:

  • break — immediately exit the entire loop.
  • continue — skip the rest of this pass and jump to the next one.
// break: stop as soon as we hit 3
for (int i = 1; i <= 10; i++)
{
    if (i == 3)
    {
        break;   // leave the loop entirely
    }
    Console.WriteLine(i);
}
// prints 1, 2
// continue: skip even numbers, print only odds
for (int i = 1; i <= 6; i++)
{
    if (i % 2 == 0)
    {
        continue;   // skip to the next pass
    }
    Console.WriteLine(i);
}
// prints 1, 3, 5

💡 The difference in one sentence

break ends the loop; continue ends only the current pass and keeps looping. Use them sparingly and clearly — overusing them can make a loop hard to follow.

Exercise & Quiz

🏋️ Exercise: Sum and Countdown

Objective: Practice both a counting loop and a condition-driven loop.

Instructions:

  1. Create a new project called Loops.
  2. Part A (for): Use a for loop to add up the numbers 1 through 10, then print the total.
  3. Part B (for, countdown): Use a for loop to print a countdown from 5 down to 1, then print "Liftoff!".
  4. Part C (while): Ask the user to type numbers, adding each to a running total, and stop when they enter 0. Print the total. (Hint: read and parse inside a while loop.)

Starter Code:

// Part A: sum 1..10
int total = 0;
for (int i = 1; i <= 10; i++)
{
    // TODO: add i to total
}
Console.WriteLine($"Sum 1..10 = {total}");

// Part B: countdown 5..1
// TODO: for loop that counts down, then print "Liftoff!"

// Part C: sum user numbers until 0
// TODO: while loop reading numbers, stop on 0
💡 Hint

To count down, start high and decrease: for (int i = 5; i >= 1; i--). For Part C, read a number before the loop or use a value that starts non-zero, then keep reading inside the loop while it isn't 0.

✅ Solution
// Part A: sum 1..10
int total = 0;
for (int i = 1; i <= 10; i++)
{
    total += i;
}
Console.WriteLine($"Sum 1..10 = {total}");   // 55

// Part B: countdown 5..1
for (int i = 5; i >= 1; i--)
{
    Console.WriteLine(i);
}
Console.WriteLine("Liftoff!");

// Part C: sum user numbers until 0
int runningTotal = 0;
Console.Write("Enter a number (0 to stop): ");
int n = int.Parse(Console.ReadLine());
while (n != 0)
{
    runningTotal += n;
    Console.Write("Enter a number (0 to stop): ");
    n = int.Parse(Console.ReadLine());
}
Console.WriteLine($"Total = {runningTotal}");

Sample run of Part C:

Enter a number (0 to stop): 5
Enter a number (0 to stop): 10
Enter a number (0 to stop): 0
Total = 15

🎯 Quick Quiz

Question 1: What is the key difference between while and do-while?

Question 2: What commonly causes an infinite loop?

Question 3: Inside a loop, what does continue do?

Summary

🎉 Key Takeaways

  • Loops repeat a block of code. Every loop needs a start, a condition, and an update so it eventually stops.
  • while checks first (may run zero times); do-while checks last (runs at least once).
  • for bundles start/condition/update on one line — ideal for counting a known number of times.
  • foreach visits every item in a collection without managing an index.
  • break exits a loop; continue skips to the next pass. Watch out for infinite loops caused by a missing update.

📚 Additional Resources

🚀 What's Next?

You can now branch and repeat — the two pillars of control flow. In Lesson 3.3: Methods, you'll learn to package code into named, reusable building blocks so your programs stay organized as they grow.

🎉 Repetition mastered!

You've now got decisions and loops. Next, we'll make your code tidy and reusable with methods.