Computational constructsRepetition and iteration

Programs run in sequences. Selection statements and loops are used in programs, allowing software to make decisions and repeat actions. These are called computational constructs

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.

There are two different types of loops 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 write some code that will print "Happy birthday" on the screen 10 times you could use a fixed loop.

Count control

Fixed loop using REPEAT..END REPEAT

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

Fixed loops can also be used to check each item in an array as part of a loop. Here are two examples, both using fixed loops to repeat a specific sequence of code a set number of times while using values held inside an array.

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 storing a list of heights. The fixed loop does not make use of counter to point to the location of the values in the array but instead takes each height value that exists one after the other.