C# Foundations · Lesson 6

Loops

A for loop repeats while its condition stays true.

A loop is a state transition with a stopping rule

A for loop places initialization, a condition, and an iteration step next to one another. Initialization runs once before the first condition check. The body runs only while that condition is true, and the iteration step runs after each completed body. These parts describe the control flow; the body describes the work. Separating them mentally makes it easier to predict whether the loop stops and which values it processes rather than treating repetition as something the runtime simply figures out.

The example also uses an accumulator: total retains a result across iterations. Its lifetime begins outside the loop so each visit can build on the previous visit's value. The loop variable i represents the current contribution, not the accumulated answer. The essential invariant here is that, after processing a value of i, total equals the sum of all integers processed so far. An invariant turns a list of assignments into a statement you can check at every step.

Trace the checks and the additions

Initially, total is zero and i is one. The condition i <= 3 succeeds, so the first body adds one and leaves total at one. The iteration step increments i to two. The next body adds two and leaves total at three. After i becomes three, the final successful visit adds three and leaves total at six. These are three body executions, not four: the initialization value zero belongs to total, not to i.

After the third body, i++ changes i to four. The condition is checked again and is now false, so the body is skipped and execution continues after the loop. The single WriteLine then prints 6. Nothing inside the original loop prints intermediate totals. Distinguish the number of condition checks from the number of body executions: this loop checks its condition once more to discover that work is finished, without performing another addition or producing another output line.

for (var i = 1; i <= 3; i++)
{
    total = total + i;
}

The comparison and the update are both part of correctness

Changing <= to < excludes three and changes the total to three. Removing the increment prevents progress toward a false condition and can leave the program running until SharpRune's execution boundary or Stop terminates it. Moving total = 0 into the body resets the accumulated state on every visit, producing a different algorithm. These mistakes have different causes, so diagnose them by tracing the control variable and accumulator separately rather than making random changes until the output looks familiar.

Change the range, then change the state lifetime

First change the upper boundary from three to five. Predict the visited values and the final total before running; the result should be fifteen. Add a temporary WriteLine inside the body that prints both i and total after the addition. Hint: the observed pairs should be 1:1, 2:3, 3:6, 4:10, and 5:15 if you use that compact format. Remove the temporary tracing afterward so the final result is easy to distinguish from diagnostic output.

Next make the loop process the values two, four, and six by starting at two, ending at six, and advancing by two. The total should be twelve. Then intentionally move the accumulator initialization into the body and explain why the previous invariant no longer holds. Hint: mark where each variable is created and which value survives to the next visit. Restore the correct lifetime and test an empty range, where the initial condition is false and the total remains zero.

Prove that the loop does the intended work

Give a complete trace with the initial state, every accepted i value, the resulting total, and the first rejected i value. You should be able to explain the final six without relying on a screenshot of the output. For a new loop, identify a progress measure and an input case that performs no iterations. Those two checks reveal many boundary and termination mistakes before a larger calculation makes them harder to see.

  • Initialization happens once, before the first condition check.
  • The original body processes one, two, and three.
  • The failed check at four performs no addition.
  • The accumulator must survive across the intended iterations.

A working example

var total = 0;
for (var i = 1; i <= 3; i++)
{
    total = total + i;
}
Console.WriteLine(total);

Expected output

6
Try this
Check that the condition becomes false.

Further reading