Loops: The Repeating Robot

Loops: The Repeating Robot in C#: A loop is a robot arm on a production line, repeating one motion. The only question is what tells it when to stop.

The Analogy: The Robot on the Line

A loop is a robot arm on a production line, repeating one motion. The only question is what tells it when to stop.

A for loop counts laps: three bolts, then down tools. A while loop watches a gauge: keep going while the pressure is above the mark, which might be zero passes or a thousand. A do / while loop is the same gauge, checked after the motion, so the arm always moves at least once. A foreach loop empties a crate: one pass per item, no counting, no chance of reaching past the end.

Picking the wrong one still works but reads badly. Counting an array by hand when foreach would do invites an off-by-one; using while for a fixed three laps hides the count in two places. The four forms exist so that the shape of the code announces the shape of the repetition.


Syntax or Core Structure

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 3; i++)
            Console.WriteLine($"for pass {i}");

        int countdown = 3;
        while (countdown > 0)
        {
            Console.WriteLine($"while {countdown}");
            countdown--;
        }

        int attempts = 0;
        do
        {
            attempts++;
            Console.WriteLine($"do attempt {attempts}");
        }
        while (attempts < 2);

        string[] parts = { "head", "body", "tail" };
        foreach (string p in parts)
            Console.WriteLine($"foreach {p}");

        for (int i = 0; i < 6; i++)
        {
            if (i % 2 == 0) continue;    // skip the even numbers
            if (i > 4) break;            // stop once past 4
            Console.WriteLine($"odd {i}");
        }
    }
}

Output:

for pass 1
for pass 2
for pass 3
while 3
while 2
while 1
do attempt 1
do attempt 2
foreach head
foreach body
foreach tail
odd 1
odd 3

The last loop is worth tracing. i = 0 is even so continue skips to the next pass; i = 1 prints; i = 2 skips; i = 3 prints; i = 4 skips; i = 5 is odd but greater than 4, so break ends the loop before printing. continue goes to the next iteration, break leaves the loop entirely — and in a for loop continue still runs the i++ step, which is not true of the equivalent while.

FormStops whenRuns at least onceReach for it when
forthe counter passes a limitnoyou need the index, or a fixed count
whilea condition goes falsenothe number of passes is unknown
do / whilea condition goes falseyesthe first pass is unconditional
foreachthe sequence is exhaustednoyou just want every item

Technical Depth: What Each Loop Really Is

The three parts of a for header

for (int i = 0; i < n; i++)      // initialiser; condition; iterator
for (int i = n - 1; i >= 0; i--) // backwards
for (int i = 0; i < n; i += 2)   // every other
for (int i = 0, j = n - 1; i < j; i++, j--)   // two counters
for (;;) { if (Done()) break; }  // all three parts are optional

The initialiser runs once, the condition is tested before every pass including the first, and the iterator runs after every pass. Declaring the counter in the header rather than above it keeps it out of the surrounding scope, which is why for (int i = ...) is the standard form.

foreach is a pattern, not a keyword trick

foreach (string p in parts) { Use(p); }

// what the compiler writes, roughly
var e = parts.GetEnumerator();
try
{
    while (e.MoveNext())
    {
        string p = (string)e.Current;   // read-only
        Use(p);
    }
}
finally { (e as IDisposable)?.Dispose(); }

Any type with a suitable GetEnumerator() can be used with foreach; implementing IEnumerable<T> is the usual way to get one. Two consequences follow directly from that expansion.

The iteration variable is read-only. p = "other"; inside the body is CS1656, because p is re-created from Current on every pass and assigning it would change nothing.

The collection must not change shape while you iterate it.

var list = new List<int> { 1, 2, 3, 4 };

foreach (int x in list)
    if (x % 2 == 0) list.Remove(x);      // InvalidOperationException

for (int i = list.Count - 1; i >= 0; i--) // safe: walk backwards by index
    if (list[i] % 2 == 0) list.RemoveAt(i);

list.RemoveAll(x => x % 2 == 0);          // better: say what you mean

List<T> keeps a version number and its enumerator throws the moment it changes. Iterate a copy (foreach (int x in list.ToList())), walk backwards by index, or use RemoveAll.

For arrays and List<T> the enumerator is a struct, so foreach over them allocates nothing and costs about what an index loop costs. Over an IEnumerable<T> interface it does allocate, which matters only in genuinely hot code.

Building strings in a loop

string s = "";
for (int i = 0; i < 10_000; i++) s += i;         // 10,000 new strings

var sb = new StringBuilder();
for (int i = 0; i < 10_000; i++) sb.Append(i);   // one growing buffer
string result = sb.ToString();

Strings are immutable, so += allocates a fresh string of the combined length on every pass — quadratic work and quadratic garbage. StringBuilder is the fix, and the threshold at which it matters is lower than most people guess.

Loop variables and closures

var actions = new List<Action>();

for (int i = 0; i < 3; i++)
    actions.Add(() => Console.Write(i));      // prints 333 - one shared i

foreach (int i in new[] { 0, 1, 2 })
    actions.Add(() => Console.Write(i));      // prints 012 - fresh i per pass

A for loop has one variable that changes; a lambda captures that variable, not its value at the time. A foreach variable is a new one on each pass, so each lambda captures its own. Copy to a local (int copy = i;) inside a for body when you need the foreach behaviour.

Ranges

int[] xs = { 10, 20, 30, 40, 50 };

foreach (int x in xs[1..4])   // 20, 30, 40 - end is exclusive
    Console.Write($"{x} ");

Console.WriteLine(xs[^1]);    // 50 - one from the end

Since C# 8 an index or range can be used to loop over part of a collection without arithmetic on the bounds, which removes another opportunity for off-by-one errors.


Real World Example: A Retry Loop

Retrying a flaky operation needs two loops nested: an outer one over the work, and an inner one over the attempts. The inner one is a do / while because the first attempt is never conditional.

using System;
using System.Text;

class Program
{
    const int MaxAttempts = 3;

    // A deterministic stand-in for a flaky call:
    // job n finally succeeds on attempt SucceedsOn[n].
    static readonly int[] SucceedsOn = { 1, 3, 4, 2 };

    static bool TryRun(int job, int attempt) => attempt >= SucceedsOn[job];

    static void Main()
    {
        var report = new StringBuilder();
        int done = 0, failed = 0, totalAttempts = 0;

        for (int job = 0; job < SucceedsOn.Length; job++)
        {
            int attempt = 0;
            bool ok;

            do
            {
                attempt++;
                totalAttempts++;
                ok = TryRun(job, attempt);
                report.AppendLine($"job {job} attempt {attempt}: {(ok ? "ok" : "retry")}");
            }
            while (!ok && attempt < MaxAttempts);

            if (ok)
            {
                done++;
            }
            else
            {
                failed++;
                report.AppendLine($"job {job} gave up after {attempt}");
            }
        }

        Console.Write(report.ToString());
        Console.WriteLine($"done {done}, failed {failed}, attempts {totalAttempts}");
    }
}

Output:

job 0 attempt 1: ok
job 1 attempt 1: retry
job 1 attempt 2: retry
job 1 attempt 3: ok
job 2 attempt 1: retry
job 2 attempt 2: retry
job 2 attempt 3: retry
job 2 gave up after 3
job 3 attempt 1: retry
job 3 attempt 2: ok
done 3, failed 1, attempts 9

Job 2 wanted a fourth attempt and the ceiling is three, so it is the one failure. The attempt counts are 1, 3, 3 and 2, which is the 9 in the summary line.

do / while is the right form here. An attempt always happens, so testing the condition first would mean either duplicating the call before the loop or initialising ok to a lie. The exit condition !ok && attempt < MaxAttempts says both reasons to stop in one place: success, or exhaustion.

The bounded retry is deliberate. A while (!ok) loop around a network call is an outage amplifier — it hammers a struggling service forever. A real implementation would also wait between attempts, with the delay growing each time (Task.Delay(baseDelay * attempt), covered in Module 7), so that retries spread out rather than pile up.

SucceedsOn replaces randomness with a table. A loop that depends on Random cannot be tested, and its failures cannot be reproduced. Making the flakiness data means the expected output above is a fact rather than a hope.

The report is a StringBuilder, not a growing string. Ten lines would not care, but a job runner with ten thousand would, and writing it correctly the first time costs nothing.


Common Mistakes

  1. Off by one at the top of an array. for (int i = 0; i <= xs.Length; i++) throws IndexOutOfRangeException on the final pass, because the last valid index is Length - 1. Use < with Length, or use foreach.
  2. Forgetting to advance a while. Leaving out countdown-- gives a loop that never ends. If the variable in the condition is not changed in the body, the loop is infinite by construction.
  3. continue before the increment in a while. In a for loop continue still runs the iterator, but in a while it jumps straight back to the condition — so a continue placed above i++ hangs the program.
  4. Mutating a collection inside foreach. Adding or removing during iteration throws InvalidOperationException. Iterate a copy, walk backwards by index, or use RemoveAll.
  5. Trying to assign the foreach variable. It is read-only (CS1656), and even if it were not, the change would be discarded on the next pass. Use an indexed for loop when you need to write back into the collection.
  6. Building a string with += in a loop. The work is quadratic in the number of passes. StringBuilder turns it back into linear.
  7. Capturing a for variable in a lambda. All the lambdas share one variable and see its final value. Copy it to a fresh local inside the body first.
  8. Nesting without noticing the cost. Two loops over the same 10,000-item list is 100 million comparisons. A HashSet or Dictionary lookup usually replaces the inner loop entirely.

Best Practices

  • Use foreach unless you genuinely need the index, a non-unit step, or to write into the collection. It cannot run off the end and it states the intent.
  • Declare the counter inside the for header so it does not leak into the surrounding scope and cannot be reused by accident.
  • Keep loop bodies short. When a body grows past a dozen lines, extract a method that takes one item — the loop then reads as a sentence.
  • Bound every loop that waits on the outside world. A retry, a poll or a read loop needs a maximum count or a deadline, or one bad day becomes an infinite one.
  • Prefer while (true) with an explicit break to a condition you have to negate mentally, and put the break where a reader will find it.
  • Compute invariants before the loop, not inside it. Hoisting a .ToUpper() or a compiled Regex out of the body is often the entire optimisation.
  • Use StringBuilder for text assembled over more than a few passes, and a pre-sized collection (new List<int>(count)) when the final size is known.
  • Consider whether LINQ says it better: items.Where(x => x.Active).Select(x => x.Name) replaces a loop, a condition and an accumulator with one readable line. Keep the explicit loop for hot paths and for anything with side effects.

Practice Exercises

  1. Print the times table for 7 up to 12 three times: once with for, once with while, and once with foreach over Enumerable.Range(1, 12). Confirm all three produce identical output.
  2. Write a loop that sums only the even numbers in { 3, 8, 12, 7, 4, 9 } using continue to skip the odd ones, then rewrite it with a single condition and no continue. State which reads better.
  3. Remove every negative number from a List<int> three ways: with a backwards indexed loop, with foreach over a copy, and with RemoveAll. Then show that the naive foreach with Remove throws, and print the exception type.
  4. Extend the retry runner so each job records its own attempt count in an array, raise MaxAttempts to 4, and hand-work the expected output before running it. Explain why job 2 now succeeds.