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.
Fixed loop using REPEAT..END REPEAT
The code needed to implement the above design is:
REPEAT 10 TIMESSEND “Happy birthday” TO DISPLAYEND REPEATUsing 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 DOSEND “Please enter your score” TO DISPLAYRECEIVE score [counter] FROM (INTEGER) KEYBOARDEND FORThis 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 DOIF height > 13 THENSET overThirteen TO overThirteen + 1END IFEND FOR EACHIn 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.