Simvik

Fix: the countdown never ends

A loop counting down to zero with an unsigned counter can never stop. An easy embedded C problem (Decisions and loops), run and graded in the browser.

easy · Decisions and loops · find-the-bug · unsigned · loops

Bug report. countdown(n) should print n, n - 1 and so on down to 0, then a new line. On the device it prints the numbers and then keeps going, 255, 254, … forever, until the watchdog resets the board. Fix it by changing one line.

Starter code

void countdown(uint8_t n) {
  for (uint8_t i = n; i >= 0; i--) printf("%u ", i);
  printf("\n");
}

Example tests

Count down from 3

countdown(3);

Expected output:

3 2 1 0

Learn it first

  • Decisions and loops · Choosing with if and switch, repeating with while and for, and the loop that never ends.

More Decisions and loops problems