Count-controlled loops
There are two ways in which programSequences of instructions for a computer. can iterationIn computer programming, this is a single pass through a set of instructions. 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 algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. for adding up five inputted numbers:
- set the total to 0
- repeat this section five times
- input a number
- add the number to the total
- go back to step 2
- 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 is so called because it uses a counterA device which stores (and/or displays) the number of times a particular event or process has occurred. to keep track of how many times the algorithm has iterated. The pseudocode Also written as pseudo-code. A method of writing up a set of instructions for a computer program using plain English. This is a good way of planning a program before coding. 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 indentingAdding spaces or tabs in front of blocks of code, making it easier for programmers to see which parts of the code relate to each other.. 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.