C Workshop · Loops
Foundation C

for, while, do-while

A loop repeats a body until a condition fails. for is counting, while is 'as long as', do-while runs the body at least once.

What it is

A loop repeats a block of code until a condition fails. C has three spellings: for (count something), while (keep going as long as), and do-while (do it once, then maybe again). This run shows for; the cards explain the family.

Approach

  1. Set the start value.
  2. Keep going while the test is true.
  3. Do the work (print / add).
  4. Step (i++ or n--).

Where this is used in the real world

Diagram

C has three loop statements. This run uses for. The cards are the other two; the numbered column is the for-loop you are about to execute.

for

Best when the count is known. Init, test, and step live in one header: for (i = 1; i <= n; i++).

while

Best when you wait on a condition. You must change the variable yourself: while (n > 0) { printf("%d", n); n--; }.

do-while

Runs the body once before testing. Typical for a menu: show choices, then ask "again?". do { work(); } while (again);

1

i = 1

initialize once

This happens before the first test, not on every pass.
2

i <= 3 ?

test before the body

If false, leave the loop. If true, run printf.
3

printf i

loop body

This pass writes the current i to stdout.
4

i++

step, then test again

i becomes 2, then 3, then 4 — and 4 fails the test.

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    int i;
4    for (i = 1; i <= 3; i++) {
5        printf("%d\n", i);
6    }
7    return 0;
8}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. This foundation run uses which loop?

for (i = 1; i <= 3; i++).

2. do-while is different because:

Test at the bottom.

3. Forgetting i++ in a while that needs it causes:

The test never fails.

4. Output of this demo is:

printf each pass.

5. break inside a loop:

Jump out of the loop.