Count Down

Like a space launch, we'd like to count down from 10.

How to make a loop? A loop is part of the program that is repeated over and over even though it is only written once. Sometimes there is a special statement for making loops. See also Tail Recursion.

How to increment a counter? A counter changes value each time through the loop. Sometimes a loop statement has a built-in counter. Sometimes it is easy to make the counter run backwards or count by more than one.

How to stop a loop from looping? A test must be made each pass through a loop to see if it is time to stop. See also Unwinding Loops. A common mistake is to write this test wrong and be Off By One in the count.

  • set counter to 10
  • begin loop
  • print counter
  • set counter = counter - 1
  • repeat loop unless counter equals 0
  • Notice that the loop enters at the top and exits at the bottom. This is considered well behaved.

    Notice that the first test is made after doing the loop once. This means that the loop will run even if the termination condition is already met.

    Notice that the initial counter value is lost. In this case we can assume that the counter is zero at the end of the loop. It is, however, considered bad practice to assume anything about the loop counter outside the loop.