Lesson 5 • Beginner Track
Loops
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.
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
if statements and comparison operators like <, <= and ==, because every loop uses a condition to decide when to stop.💡 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?
| 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 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.
Worked example: counting with for
Count up, count down, skip by 2, and build a times table — read each comment and check the output.
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}");
...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.
🎯 Your turn: sum 1 to 5 with a for loop
Fill in the loop header (start, condition, step), then check the total is 15.
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, ste
...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.
Worked example: while & do-while
Halve a number until it drops below 1, then run a menu that always shows 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; // <--
...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").
Worked example: foreach, break & continue
Iterate a list, break on the first even number, and continue past negatives.
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
...Now you try. The loop below should total only the positive numbers and skip the negatives. Fill in the two ___ blanks:
🎯 Your turn: total the positives with continue
Pick the array to loop over and the keyword that skips an item, then check the total is 60.
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
...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.
Worked example: nested loops
Print a star grid and a multiplication table — watch how the inner loop restarts for every outer pass.
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
{
...🔎 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.
Worked example: scoreboard
Change the scores and watch the average, top score, and first distinction update.
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
...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
- 💡 Prefer foreach over for when iterating collections: it's cleaner and avoids off-by-one index errors entirely.
- 💡 Use
i < array.Length, not a hard-coded count: the loop then adapts automatically if the array's size changes. - 💡 Consider LINQ instead of a loop for filtering:
numbers.Where(n => n > 5)is often clearer than a loop withcontinue. - 💡 Avoid modifying a collection inside foreach: it throws
InvalidOperationException. Use aforloop, or copy withToList()first, if you need to remove items. - 💡 In nested loops,
breakonly exits the innermost loop — restructure or use a flag if you need to exit both.
Common Errors (and the fix)
- Infinite loop (program hangs): you forgot to update the counter —
while (i < 5) { Console.WriteLine(i); }never ends becauseinever changes. Make sure something inside the loop moves it toward the stopping condition (e.g.i++). - Off-by-one with
<vs<=:for (int i = 0; i <= 5; i++)runs 6 times (0–5), not 5. For "5 times starting at 0" usei < 5; for "1 to 5 inclusive" usei <= 5. - "System.InvalidOperationException: Collection was modified": you added to or removed from a list inside a
foreachover it. Loop over a copy (list.ToList()) or use aforloop counting downwards. - "CS0103: The name 'i' does not exist in the current context": the loop variable from
for (int i ...)only exists inside the loop. If you need the value afterwards, declare it before the loop. - Can't change items in foreach: the
foreachvariable is read-only —foreach (var x in list) x = 0;won't compile. Use aforloop and assign via the index:list[i] = 0;.
📋 Quick Reference
| Task | Code | Result |
|---|---|---|
| Count 1 to 5 | for (int i = 1; i <= 5; i++) | 1,2,3,4,5 |
| Count 0 to 4 | for (int i = 0; i < 5; i++) | runs 5 times |
| Step by 2 | i += 2 | 2,4,6,... |
| Loop until condition | while (x >= 1) | may run 0 times |
| Run at least once | do { ... } while (cond); | always 1+ runs |
| Walk an array | foreach (int n in nums) | each element |
| Exit early | break; | leaves the loop |
| Skip this one | continue; | 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.
🎯 Mini-Challenge: sum 2+4+...+20
Write the loop yourself and print the total (it should be 110).
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)
...🎉 Lesson Complete
- ✅
for (init; condition; step)— best for counted iterations and number ranges - ✅
whilechecks the condition first, so it may run zero times - ✅
do-whileruns the body first — always executes at least once - ✅
foreachis the cleanest way to walk arrays, lists, and collections - ✅
breakexits the loop immediately;continueskips to the next iteration - ✅ Nested loops handle grids and tables — the inner loop restarts for every outer pass
- ✅ Watch for infinite loops, off-by-one (
<vs<=), and modifying a collection insideforeach - ✅ Next lesson: Methods — organise your code into reusable, named functions
Sign up for free to track which lessons you've completed and get learning reminders.