Implementation: Computational constructsRepetition and iteration

Programs use computational constructs such as loops and predefined functions to break programs up into sections. This makes programs more compact, easier to write and easier to maintain.

Part ofComputing ScienceSoftware design and development

Repetition and iteration

Repetition in a program means that lines of code will be run multiple times.

Iteration is a term similar to repetition. It means to continue repeating an action until you achieve the correct outcome, unless that desired outcome is not possible.

Both iteration and repetition are implemented using loops.

There are two different types of loop that you can use:

Fixed loop - This is where the loop repeats a sequence of code a set number of times.

Conditional loop - This kind of loop keeps repeating code until a condition is met.

Fixed loop

A fixed loop can be used to repeat the same sequence of code a set number of times. If you want to design a solution that will print "Happy birthday" on the screen 10 times you could use a fixed loop.

Count control

Fixed loop using REPEAT..END REPEAT

The code needed to implement the above design is:

REPEAT 10 TIMES
SEND “Happy birthday” TO DISPLAY
END REPEAT

Using a loop to access each item in an array in sequence is known as traversing an array. Here are two examples, both using fixed loops to repeat a specific sequence of code.

Fixed loop using FOR..FROM..TO..END FOR

FOR counter FROM 0 TO 4 DO
SEND “Please enter your score” TO DISPLAY
RECEIVE score [counter] FROM (INTEGER) KEYBOARD
END FOR

This fixed loop will repeat 5 times (0 to 4). This code will ask the user to enter their score. Once it has asked the user to do this five times the loop will stop running as it can only run a fixed number of times (in this example five times).

Fixed loop using FOR..EACH..FROM..DO..END FOR EACH

DECLARE allHeights AS ARRAY OF REAL INITIALLY [12.1, 14.5, 16.2, 11.3, 9.1]
FOR EACH height FROM allHeights DO
IF height > 13 THEN
SET overThirteen TO overThirteen + 1
END IF
END FOR EACH

In the above example, an array has been created to store a list of building heights. A fixed loop is then used to check each item in the array (traverse the array). If what is held in the array is greater than thirteen, then one is added to the total number of heights over thirteen.