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.
Fixed loop using REPEAT..END REPEAT
REPEAT 10 TIMESSEND “Happy birthday” TO DISPLAYEND REPEATFixed 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 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 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.