Condition-controlled loops
A condition-controlled loop is so called because iteration continues while, or until, a conditionIn computing, this is a statement or sum that is either true or false. A computation depends on whether a condition equates to true or false. is met.
Consider this simple algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. for entering a correct password:
- enter password
- unless password = 鈥渋lovecomputing鈥, go back to step 1
- say 鈥楶assword 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 pseudocode Also written as pseudo-code. A method of writing up a set of instructions for a computer program using plain English. This is a good way of planning a program before coding. 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 indentingAdding spaces or tabs in front of blocks of code, making it easier for programmers to see which parts of the code relate to each other.. Indentation is used to show which steps are to be iterated.
In this example, the condition is whether or not the inputted password equals 鈥渋lovecomputing鈥. 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.