鶹Լ

Count-controlled loops

There are two ways in which can or ‘loop’:

  • count-controlled loops
  • condition-controlled loops

Each type of loop works in a slightly different way and produces different results.

Count-controlled loops

Sometimes it is necessary for steps to iterate a specific number of times.

Consider this simple for adding up five inputted numbers:

  1. set the total to 0
  2. repeat this section five times
    • input a number
    • add the number to the total
  3. go back to step 2
  4. say what the total is

This algorithm would allow five numbers to be inputted and would work out the total. Because it is known in advance how many times the algorithm needs to loop, a count-controlled loop is used.

A count controlled loop continues a predefined number of times. At a race track, a car might be given the rules, loop 52 times, then stop.

A count-controlled loop is so called because it uses a to keep track of how many times the algorithm has iterated. The for this algorithm might look like this:

total to 0
count to 1
FOR as long as count is in the range 1 to 5
	INPUT user inputs a number
	STORE the user's input in the number variable
	total = total + number
	Add 1 to count
OUTPUT "The total is " + total

Steps that are part of the loop are . Indentation is used to show which steps are to be iterated.

In this example, the variable ‘count’ is used to keep track of how many times the algorithm has iterated. This variable controls the loop. The algorithm will continue to iterate until the value of count has reached 5. As soon as count reaches 5, the algorithm stops iterating.