Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 182 ยท Operators and Control Flow

while, do-while and for Loops

Learn the three classic C# loops - while, do-while and for - with loop variable scope, nested loops, infinite loops with break, loop invariants and how to avoid off-by-one errors.

Computers are good at repetition. Printing a table of 1,000 prices, reading lines until the input runs out, retrying a failed download three times: all of this needs a loop, a block of code that runs again and again while some condition holds. C# has four loop statements. This lesson covers the three classic ones, while, do-while and for; the fourth, foreach, has its own lesson.

You will learn how each loop works step by step, which one to choose, how the scope of loop variables works, how to write infinite loops safely, how nested loops behave, and how to think in loop invariants so that off-by-one errors stop surprising you.

while: repeat as long as a condition is true

A while loop checks its condition before every pass. If the condition is false the very first time, the body never runs.

C# Counting with while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Follow it step by step: count starts at 1; the condition 1 <= 5 is true, so the body prints and increments; this repeats until count becomes 6, the condition fails and execution continues after the loop. The final line prints 6, not 5, which is a good reminder that after a loop the variable holds the first value that failed the test.

Every while loop needs something inside the body that eventually makes the condition false. Forget count++ and the program spins forever (see "Infinite loops" below).

while is the right choice when you do not know in advance how many passes you need, for example "keep reading until the input ends":

C# Reading lines until the input ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The condition both reads a line and tests it. Console.ReadLine() returns null at the end of the input, which ends the loop. The assignment-inside-condition idiom is common here, but keep the parentheses around the assignment.

do-while: run at least once

A do-while loop checks its condition after the body, so the body always runs at least once. Note the semicolon after the closing parenthesis.

C# do-while for input validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You cannot validate an answer before you have asked the question, which is why do-while fits menus, retry loops and "ask until valid" prompts. In practice it is much rarer than while and for. Notice that number is declared before the loop: variables declared inside the braces are not visible in the condition after the closing brace.

If the input ended before a valid answer arrived, ReadLine would return null, and the loop above would run forever. Production code should also stop at the end of the input.

for: when you know the count

A for loop packs the three loop ingredients into one line: initializer, condition and iterator.

TEXT
for (initializer; condition; iterator)
{
    body
}
  1. The initializer runs once, before the first pass.
  2. The condition is tested before each pass; when false, the loop ends.
  3. After each pass, the iterator runs, then back to step 2.
C# The anatomy of a for loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The loop runs for i equal to 0, 1, 2, 3, 4: five passes. The pattern for (int i = 0; i < n; i++) is the idiom for "do something n times" and for walking through an array by position. All three parts are optional and can contain several expressions:

C# Two variables and counting down

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first loop prints 10 7 4 1. The second one is the classic two-pointer pattern (used to reverse arrays or check palindromes): it stops when the pointers meet. Use the index-based form of the loop when you need the position or want to modify elements. For plain reading, foreach is simpler.

Scope of the loop variable

A variable declared in the initializer lives only inside the for statement. You cannot use it afterwards, and you may reuse the name in a later loop.

C# The loop variable does not leak (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This stops with error CS0103: The name 'i' does not exist in the current context. If you need the final value, declare the variable before the loop (int i; for (i = 0; ...)). Two sibling loops can both declare int i without conflict because each one has its own scope. Declaring i in an inner scope while an outer i exists is an error, though.

Never change the loop counter by accident

Changing the counter inside the body is legal and sometimes useful (skipping an item), but it is a common source of bugs. Prefer continue (jumps) when you want to skip, and keep the counter's changes in the iterator part so a reader can see the whole story in one line.

Infinite loops and break

Sometimes a loop has no natural end: a game loop, a server waiting for requests, a retry until success. Write it as while (true) (or for (;;)) and leave through break, return or throw when the work is done.

C# An infinite loop that ends with break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Make sure every infinite loop has a visible exit. In a real application, a loop that waits for something should also check a cancellation signal or a maximum number of attempts. An accidental infinite loop in our online editor is stopped by the five-second limit; on your own machine, press Ctrl+C.

Nested loops

A loop inside another loop runs completely for every pass of the outer loop. If the outer loop runs 3 times and the inner one 4 times, the inner body runs 12 times.

C# A multiplication table with nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The format {row * col,4} right-aligns each number in a field of four characters; see console output. Nested loops multiply work: a loop of n inside a loop of n does n squared steps. For 1,000 items that is a million steps, for 100,000 items it is ten billion, which is why algorithms with nested loops over the same large collection are a classic performance problem. Often a dictionary or a set (collections) removes the inner loop.

To leave both loops at once you need more than one break; the options are covered in break, continue, goto and return.

Loop invariants and off-by-one errors

The most common loop bug is being off by one: running one time too many or too few, or reading one element past the end. Compare:

  • i < n stops before n: indexes 0 to n-1, exactly n passes.
  • i <= n includes n: n+1 passes starting from 0. For an array of length n that reads array[n], which does not exist.

Arrays that are accessed past the end throw IndexOutOfRangeException:

C# One step too far (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last pass has i == 3, and the program ends with Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.. The fix is i < data.Length.

A reliable way to avoid these mistakes is to think about the loop invariant: a statement that is true before the loop and after every pass. For summing, the invariant is "sum equals the total of the first i elements". Before the loop i is 0 and sum is 0: true. Each pass adds data[i] and increases i, so it stays true. When the loop ends with i == data.Length, the invariant says sum is the total of all elements. You prove correctness without running the code.

C# Checking an invariant while looping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Keep these habits: use half-open ranges (start included, end excluded) as C# does throughout; test the empty case (zero passes) and the single-element case; and when you write the condition, ask "what is the value of the counter when the loop ends?".

Which loop should I use?

Situation Loop
You know the number of passes, or you walk by index for
Repeat until something happens, possibly zero times while
Do something first, then decide whether to repeat do-while
Visit every element of a collection foreach
Never ends by itself (game loop, server) while (true) with break/return

Loops over collections can often be replaced by LINQ (Sum, Where, Any). LINQ reads well, but a plain loop is faster and allocates nothing in hot paths; measure before changing code for speed.

Do not modify a collection while you iterate over it with foreach. With a for loop over a List<T>, removing items shifts the later ones, so either loop backwards (for (int i = list.Count - 1; i >= 0; i--)) or build a new list.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between while and do-while?

    A do-while loop evaluates its condition after each pass, which guarantees one execution of the body. A while loop may run zero times.
  2. 2. How many times does for (int i = 0; i < 5; i++) run its body?

    i takes the values 0, 1, 2, 3 and 4, which is five passes. At i == 5 the condition fails.
  3. 3. What is true about a variable declared in the initializer of a for loop?

    The scope of the variable is the for statement. Using it afterwards is error CS0103, so declare it before the loop if you need its final value.
  4. 4. Which loop correctly visits every index of an array named data?

    Valid indexes are 0 to Length - 1. Using <= goes one too far, starting at 1 skips the first element, and starting at Length reads past the end.
  5. 5. A for loop with 100 passes contains another for loop with 50 passes. How many times does the inner body run in total?

    The inner loop runs fully (50 passes) for each of the 100 outer passes, so 100 x 50 = 5,000.

Summary

  • while tests first and may run zero times; do-while tests last and runs at least once; for combines initializer, condition and iterator and fits counted loops.
  • Variables declared in a for initializer disappear after the loop.
  • while (true) plus break or return is the idiom for loops with no natural end; always have a visible exit.
  • Nested loops multiply their pass counts, so look for ways to remove the inner loop on large data.
  • Prevent off-by-one errors with half-open ranges, i < Length and the loop invariant "what is true after every pass".
  • Use foreach to read every element, and never remove items from a collection while iterating over it.

Next: foreach and Iteration