大象传媒

Algorithms - EdexcelCount-controlled iteration

Algorithms are step-by-step plans for solving problems. Algorithms can be designed using pseudo-code, flowcharts, written descriptions and program code. There are also some standard algorithms for searching and sorting.

Part of Computer SciencePrinciples of computer science

Count-controlled iteration

Count-controlled repeatedly executes a section of code a fixed number of predetermined times. This is implemented using a FOR loop, which uses a control variable to determine what code is repeatedly executed and how many times. This program would also print out a message six times:

FOR count FROM 1 TO 6 DO
                    聽聽聽聽聽SEND 鈥楥oding is cool鈥 TO DISPLAY
                    END FOR

The 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鈥檚 control variable to print a value for the ten times table:

FOR count FROM 1 TO 10 DO
                    聽聽聽聽聽SEND count * 10 TO DISPLAY
                    END FOR

When 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