C Workshop · While Countdown
Lesson C

While Countdown

while repeats as long as the test stays true. You must change the variable inside the body.

What it is

A countdown prints 3, then 2, then 1, then stops. while is a natural voice here: keep going as long as n is still greater than zero, print n, then subtract one.

Approach

  1. Set n to the start value.
  2. while (n > 0) print n, then n--.
  3. Stop when n is 0.

Where this is used in the real world

Diagram

1

n=3

start

2

n>0?

test

3

print n

body

4

n--

step

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 n = 3;
4    while (n > 0) {
5        printf("%d\n", n);
6        n--;
7    }
8    return 0;
9}
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 lesson uses:

while (n > 0).

2. Output is:

Print then decrement.

3. If you forget n-- :

n stays 3.

4. A for countdown could look like:

for can count down too.

5. do-while vs this while:

Body before test.