Count-controlled iteration
Count-controlled iterationThe repetition of a block of statements within a computer program. repeatedly executionThe process of a program being run on a computer. a section of code a fixed number of predetermined times. This is implemented using a FOR loop, which uses a control variableA memory location within a computer program where values are stored. to determine what code is repeatedly executed and how many times. This 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. program would also print out a message six times:
FOR count FROM 1 TO 6 DO SEND ‘Coding is cool’ TO DISPLAY END FORThe first line of the program determines how many times the code is to be iterated. It uses a variable, in this case count, known as the control variable, to keep track of how many times the code has been repeated so far. The variable is given a starting value - in this case 1 - and an end value - in this case 6.
Every time the code is iterated, the value of count increases by one. At the end of the iteration, the value of count is tested to see if it matches the end value. If the result is FALSE, the code loops back to the start of the iteration and runs again. If it is TRUE, the iteration ends and the program continues with the next line of code.
The control variable used to initialise a FOR loop can be used within the loop itself. This program uses a loop’s control variable to print a value for the ten times table:
FOR count FROM 1 TO 10 DO SEND count * 10 TO DISPLAY END FORWhen programmers use iteration, a program is simplified, less error-prone and more flexible. This is because:
- there are fewer lines of code, which means there are fewer opportunities for typing errors to creep in
- to increase or decrease the number of iterations, only the loop's end value needs to be changed