大象传媒

Programming constructs - EduqasCount-controlled iteration

Programs are created using common building blocks, known as programming constructs. These programming constructs form the basis for all programs and are also used in algorithms.

Part of Computer ScienceSystems analysis

Count-controlled iteration

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

An explanation of iteration, as used in algorithms and programming

Iteration is also often referred to as , since the program 鈥榣oops鈥 back to an earlier line of code.

Flowchart for an algorithm for a program that prints the numbers 1 to 10

Sections of code that are iterated are called . Iteration enables programmers to greatly simplify a program. 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.

This program would print a message out six times:

print 鈥淐oding is cool鈥
                    print 鈥淐oding is cool鈥
                    print 鈥淐oding is cool鈥
                    print 鈥淐oding is cool鈥
                    print 鈥淐oding is cool鈥
                    print 鈥淐oding is cool鈥

repeatedly executes a section of code a fixed number of predetermined times. It uses the 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 鈥淐oding 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 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 is greater than 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鈥檚 condition variable to print the 10 times table:

for count = 1 to 10
                    聽聽聽聽print count * 10
                    next count

As can be seen above, using iteration makes a program simpler, 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