Algorithms - EduqasCount-controlled iteration

Algorithms are step-by-step plans for solving problems. They are a starting point when writing a program. Algorithms can be designed using pseudo-code and flowcharts.

Part ofComputer ScienceUnderstanding Computer Science

Count-controlled iteration

is the third programming construct. There are times when a program needs to repeat certain steps until told otherwise, or until a condition has been met. This process is known as iteration.

Iteration is also often referred to as , since the program ‘loops’ back to an earlier line of code. Sections of codes that are iterated are called loops.

Iteration enables programmers to greatly simplify a . Instead of writing out the same lines of code again and again, a programmer can write a section of code once, and ask the program to it again and again until no longer needed.

An explanation of iteration, as used in algorithms and programming

This program would print a message out six times:

print(“Coding is cool”)
print(“Coding is cool”)
print(“Coding is cool”)
print(“Coding is cool”)
print(“Coding is cool”)
print(“Coding is cool”)

Count-controlled iteration repeatedly executes a section of code a fixed number of predetermined times. It uses the statements for and next to determine what code is repeatedly executed and how many times. This program would also print out a message six times:

for count = 1 to 6 print(“Coding is cool”)
next count

The first line of the program determines how many times the code is to be iterated. It uses a , in this case count, known as the condition 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 one) and an end value (in this case six).

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 condition variable used to initialise a for next loop can be used within the loop itself. This program uses a loop’s condition variable to print the 10 times table:

for count = 1 to 10 print(count * 10)
next count

As can be seen above, by using iteration a program is simplified, less error prone and more flexible. This is because:

  • there are fewer lines of code, meaning fewer opportunities for typing errors to creep in
  • to increase or decrease the number of iterations, all the programmer has to do is change the loop's end value