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 code within the loop is repeated until the correct password is received from the user.
The design for a conditional loop used to check the validity of a password is shown below.
In the image shown below, the user is asked to enter the name of the subject with the coolest teachers. Only when a user enters 'Computing Science' will the program stop asking for a new answer from the user. A conditional loop would have been used, with the necessary condition being that the user enter 'Computing Science'.
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 coolestTeachers FROM (STRING) KEYBOARDWHILE coolestTeachers ≠ “Computing Science” DOSEND “Sorry. Try again” TO DISPLAYRECEIVE coolestTeachers FROM (STRING) KEYBOARDEND WHILE
In this case, the user is firstly asked to enter the name of the subject with the coolest teachers. If the first subject they enter is Computing Science, 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 Science.
If the user has not entered Computing Science on line 1, the loop is activated and will keep asking the user to try again until they enter Computing Science. 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 coolestTeachers FROM (STRING) KEYBOARDIF coolestTeachers ≠ “Computing Science” THENSEND “Sorry. Try again” TO DISPLAYEND IFUNTIL coolestTeachers = “Computing Science”
Post-test conditional loops will always run all lines at least once, even if in this case the user enters 'Computing Science' 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.