Conditional loops
A conditional loop keeps repeating until a specific condition is met. The program might keep asking a user to enter their password until they enter the right one. The loop will keep going round repeating the code until they actually enter the right password. Depending on how long it takes the user to enter the right password, the loop could go round once or one thousand times!
In the image shown below, the user is asked to enter their favourite subject. Only when they enter Computing Science will the loop stop asking for their favourite subject.
There are two ways to create conditional loops. You can use a pre-test conditional loop or a post-test conditional loop.
Pre-test conditional loop (Using WHILE…DO…END WHILE)
RECEIVE favouriteSubject FROM (STRING) KEYBOARDWHILE favouriteSubject ≠ “Computing” DOSEND “Sorry. Try again” TO DISPLAYRECEIVE favouriteSubject FROM (STRING) KEYBOARDEND WHILE
In this case, the user is firstly asked to enter their favourite subject. If the first subject they enter is Computing, the pre-test conditional loop will never run. This is because the code on line 2 will only allow the loop to run if what the user has entered is not equal to Computing.
If the user has not entered Computing on line 1, the loop is activated and will keep asking the user to try again until they enter Computing. Pre-test conditional loops are more efficient than post-test conditional loops.
Post-test conditional loop (Using REPEAT...UNTIL)
It is also possible to use a post-test conditional loop, which will always run the code within the loop at least once. This is because the actual condition needed to leave the loop is not checked until the end of the loop rather than at the start. Post-test conditional loops often make use of IF statements and are less efficient than pre-test conditional loops.
REPEATRECEIVE favouriteSubject FROM (STRING) KEYBOARDIF favouriteSubject ≠ “Computing” THENSEND “Sorry. Try again” TO DISPLAYEND IFUNTIL favouriteSubject = “Computing”
Post-test conditional loops will always run all lines least once, even if in this case the user enters “Computing” correctly on line 2.
Remember that conditional loops can also make use of logical operators such as AND and OR. It is important to remember that AND requires both conditions to be true whereas OR only requires one condition to be true. It is very common to find mistakes with the use of AND and OR when creating conditional loops.