Unit 1 · Lesson 626 minAcademic review pending

Loops you can prove will stop

Design for, while, and do-while loops using initialization, condition, update, and a trace table.

Choose explanation

After this lesson

You should be able to

  • Choose a loop based on what controls repetition.
  • Trace each iteration and detect off-by-one or non-terminating behavior.
01

Four questions for every loop

Ask: what is initialized, what condition allows another iteration, what changes, and why must the condition eventually become false? A for loop keeps these pieces together when a counter controls repetition. A while loop fits sentinel or condition-controlled repetition.

A do-while checks after the body, so it runs at least once. Use it when one attempt must happen before deciding whether to repeat, not merely because the syntax looks different.

02

Trace, do not stare

A trace table records variables after each iteration. For summing 1 through n, track i and sum. With n = 3, sum changes 0 → 1 → 3 → 6 and i changes 1 → 2 → 3 → 4.

Off-by-one errors come from mismatched starting values or bounds. Test n = 0, n = 1, and a normal value. Boundary tests reveal whether <= should have been <.

Sum 1 through n
int sum = 0;

for (int i = 1; i <= n; i++) {
    sum += i;
}

printf("%d\n", sum);

Try it yourself

Write a loop that counts how many digits are in a positive integer.

Need a hint?

Integer division by 10 removes the final decimal digit.

Check the worked solution

Start count at 0. Repeatedly divide n by 10 and increment count until n becomes 0. Handle original n = 0 separately if zero is allowed.

int count = 0;

while (n > 0) {
    n /= 10;
    count++;
}

Quick check

Which loop always executes its body at least once?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Loops · Structured programming

Maps to course outcomes CO1, CO2, CO3.