A
conditional loop (also known as an
indeterminate loop) is a loop that determines whether to terminate based on a logical condition. These loops are flexible, but their exact behavior can be difficult to reason about. A conditional loop is usually composed of two parts: a
condition and a
body. The
condition is a logical statement depending on the state of the program and the
body is a block of code that runs as long as the
condition holds. In most programming languages, the
condition is checked once for every execution of the
body. When the
condition is checked is not standardized and some programming languages contain multiple conditional looping structures with different rules about when the
condition is assessed.
Pre-test loop A
pre-test loop is a conditional loop where the
condition is checked before the
body is executed. More precisely, the
condition is checked and if it holds the
body is execute. Afterwards, the
condition is checked again, and if it holds the
body is executed again. This process repeats until the
condition does not hold. Many programming languages call this loop a
while loop and refer to it with the
keyword while. They are commonly formatted in manner similar to
while condition do body repeat Instead of the keywords
do and
repeat, other methods are sometimes used to indicate where the
body begins and ends, such as
curly braces or
whitespace. For example, the following code fragment first checks whether
x is less than five, which it is, so the
body is entered. There,
x is displayed and then incremented by one. After executing the statements in the
body, the
condition is checked again, and the loop is executed again. This process repeats until
x has the value five.
x ← 0
while x for (int i = 0; i
Equivalent constructs Assuming there is a function called
do_work() that does some work, the following are equivalent. As long as the
continue statement is not used, the above is technically equivalent to the following (though these examples are not typical or modern style used in everyday computers):
while true do do_work()
if condition is not
true then break end if repeat or LOOPSTART: do_work()
if condition then goto LOOPSTART
end if == Enumeration ==