鶹Լ

Condition-controlled loops

A condition-controlled loop is so called because iteration continues while, or until, a is met.

A condition controlled loop continues until a condition is met. At a race track, a car might be given the rules, loop until fuel run's out, then go to pitstop.

Consider this simple for entering a correct password:

  1. enter password
  2. unless password = “ilovecomputing”, go back to step 1
  3. say ‘Password correct’

This algorithm would keep iterating until the password is entered correctly. A condition-controlled loop must be used because there is no way of knowing in advance how many times a password will need to be entered before it is correct.

The for this algorithm might look like this:

password = "blank"
WHILE password does not equal "ilovecomputing"
	INPUT password
OUTPUT "Password correct"

Steps that are part of the loop are . Indentation is used to show which steps are to be iterated.

In this example, the condition is whether or not the inputted password equals “ilovecomputing”. The algorithm tests the condition to see if it is true. If true, the algorithm outputs a message. If false, the algorithm loops back to the beginning and will continue to do so until the tested condition is true.