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 .
Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, 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?
Loop
Best For
Runs at Least Once?
for
Known number of iterations, counting
No (if condition is false)
while
Dynamic condition, unknown iterations
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.
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.
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.
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").
Now you try. The loop below should total only the positive numbers and skip the negatives. Fill in the two ___ blanks:
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.
🔎 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.
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.
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 with continue .
- 💡 Avoid modifying a collection inside foreach: it throws InvalidOperationException . Use a for loop, or copy with ToList() first, if you need to remove items.
- 💡 In nested loops, break only 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 because i never 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" use i < 5 ; for "1 to 5 inclusive" use i <= 5 .
- "System.InvalidOperationException: Collection was modified": you added to or removed from a list inside a foreach over it. Loop over a copy ( list.ToList() ) or use a for loop 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 foreach variable is read-only — foreach (var x in list) x = 0; won't compile. Use a for loop 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
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.
🎉 Lesson Complete
- ✅ for (init; condition; step) — best for counted iterations and number ranges
- ✅ while checks the condition first, so it may run zero times
- ✅ do-while runs the body first — always executes at least once
- ✅ foreach is the cleanest way to walk arrays, lists, and collections
- ✅ break exits the loop immediately; continue skips 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 inside foreach
- ✅ Next lesson: Methods — organise your code into reusable, named functions
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
- Previous: Control Flow
- Next: Methods