成人快手

Iteration in programmingCondition-controlled loops

When designing programs, there may be some instructions that need repeating. This is known as iteration, and is implemented in programming using FOR and WHILE statements.

Part of Computer ScienceProgramming

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 = 鈥渋lovecomputing鈥, go back to step 1
  3. 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 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 鈥渋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.