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 .

Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.

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.

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.

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.

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).

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.

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.

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.

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.