Programs are created using common building blocks, known as programming constructs. These programming constructs form the basis for all programs and are also used in algorithms.
Condition-controlled iteration repeatedly executes a section of code until a condition is met - or no longer met. There are three types of condition-controlled iteration:
while repeatrepeat untildo loop or do whileWhile loops test the condition at the beginning of the loop. If the condition is met, the code within the loop is executed before the program loops back to test the condition again. This program would print out a message six times:
set count = 0
while count < 6
print “Coding is cool”
count = count + 1
repeat
The while statement defines the start of the loop. The repeat statement declares the end of the loop. A variable, in this case count, is used for the condition. The while statement also tests the condition, in this case to see if the value of count is less than 6. If the result is TRUE, the code within the loop is executed then the program loops back to the condition, which is tested again.
The iteration continues until the condition test result is FALSE. Once a rogue value outside of the condition has been found it will terminate the loop and the program will execute the next line of code in sequence after the loop.
Because the condition is tested at the start of the loop, it is possible for the code within it to never actually be executed. Consider this program:
set count = 6
while count < 6
print “Coding is cool”
count = count + 1
repeat
The first time the condition is tested, the result will be FALSE, as the value of count is not less than 6. Because of this, none of the code within the loop will be executed and the program will move onto the next line of code in sequence after the loop.
Repeat loops function in the same way as while loops, with one major difference - the condition is tested at the end of the loop:
set count = 0
repeat
print “Coding is cool”
count = count + 1
until count = 10
The repeat statement defines the start of the loop. The until statement tests the condition. Because the condition is tested at the end, the code within the loop is always executed at least once, even if the result of the test is FALSE.
A do while construct works in the same way as a repeat until construct and a do loop construct works in the same way as a while repeat construct.
The condition for a do construct is placed at the end of the construct, for example do … until x > 6 or do … while x < 6.
Algorithms quoted by Eduqas are unlikely to use ‘do’ constructs.