A conditional loop is a more general type of loop that allows a much wider variety of programming options. Thus it is more powerful, but can also lead to more logic errors.
Recall that conditions are statements that evaluate to either true or false. Conditions, or conditional statements, are the key to If-Then-Else Statements, and are equally important with loops. In Turing, each loop must specify an exit condition, which is the condition (or conditions) that will result in the end of the loop.
By convention, and to ensure consistent and less chaotic code, exit conditions occur only at the beginning or the end of a loop.
- In a while loop, the exit condition appears at the beginning of the loop. Depending upon the exit condition and what has happened in the program before the loop started, the loop might not even execute.
- In an until loop (sometimes called a repeat-until loop), the exit condition is tested at the end of the loop. This means the code inside the loop must execute at least once.
exit condition at beginning
(while loop)
|
exit condition at end
(until loop)
|
loop
exit when (exit condition is true)
do something 1
do something 2
do something 3
end loop
|
loop
do something 1
do something 2
do something 3
exit when (exit condition is true)
end loop
|
Sample Code (while loop - exit at beginning):
The "while loop" looks more complicated to set up, but it does a better job of handling what happens the first time, versus all of the rest of the times within the loop.
var word : string
put "What is the magic word? "..
get word
loop
exit when (word = "please")
put "Sorry, that isn't the magic word"
put "Try again... what is the magic word? "..
get word
end loop
Sample Code (until loop - exit at end):
The "until loop" is simpler to set up, but it does not handle the idea of "first time" and "rest of the times" very well.
var word : string
loop
put "What is the magic word? "..
get word
exit when (word = "please")
end loop
Comments (0)
You don't have permission to comment on this page.