大象传媒

Count controlled iteration

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 is often referred to as , since the program 鈥榣oops鈥 back to an earlier line of code. Iteration is also known as repetition.

Iteration allows programmers to simplify a program and make it more . 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 the same line repeatedly until no longer needed.

When a program needs to iterate a set number of times, this is known as count controlled iteration or and makes use of a . A FOR loop uses an extra called a that keeps track of the number of times the loop has been run.

An explanation of iteration, as used in algorithms and programming

This program would print a message out six times:

OUTPUT 鈥淐oding is cool鈥
OUTPUT 鈥淐oding is cool鈥
OUTPUT 鈥淐oding is cool鈥
OUTPUT 鈥淐oding is cool鈥
OUTPUT 鈥淐oding is cool鈥
OUTPUT 鈥淐oding is cool鈥

Count controlled iteration uses the FOR and ENDFOR 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
     OUTPUT 鈥淐oding is cool鈥
ENDFOR

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 stepper variable, to keep track of how many times the code has been repeated so far. The variable is given a starting value.

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 stepper variable used to initialise a FOR loop can be used within the loop itself. This program uses a loop鈥檚 condition variable to print the ten times table:

FOR count 鈫 1 TO 10
     OUTPUT count * 10
ENDFOR

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

FOR loops with STEP

It is also possible to add the keyword STEP to the first line of a FOR loop to determine how much the stepper variable increases or decreases by with each iteration.

The code below would output 1, 3, 5, 7, 9 as the value of count increases by two for each iteration:

FOR count 鈫 1 TO 10 STEP 2
     OUTPUT count 
ENDFOR

The code below would display 5, 4, 3, 2, 1 as the value of count decreases by one for each iteration:

FOR count 鈫 5 TO 1 STEP -1
    OUTPUT count 
ENDFOR