The function of structural components of programs - EdexcelCount-controlled iteration

Programs are designed and implemented using common building blocks, known as programming constructs. These constructs are sequence, selection and iteration and they form the basis for all programs.

Part ofComputer ScienceApplication of computational thinking

Count-controlled iteration

Count-controlled repeatedly a section of code a fixed number of predetermined times. This is implemented using a FOR loop, which uses a control 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 ‘Coding 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’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 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