Next: Summary
Up: Further Structured Design
Previous: Example Two: Using a
The while statement used above executes a statement while some condition remains true. Sometimes it is more natural to repeat something until some condition becomes true. The repetition portion of the first version of the algorithm in Section 15.2 could be written in the alternative form:
initialise. Enter first value. repeat { process value. enter a value. } until value is negative.If this version is executed using some positive values terminated by a negative value then it has exactly the same effect as the version using the while statement. However its behaviour is different if a negative number is entered first. In the repeat-until statement the termination condition is tested after the body of the loop has been executed once. Hence in this example the negative value entered first would be processed, giving a result when none was expected and then another entry value would be expected. Hence the repeat-until statement cannot be easily used in situations where it might not be necessary to execute the body of the loop. In this case it is better to use the while statement which tests a continuation condition before executing the body of the loop.
Another form of repetition control is often required, that is to repeat some statement a known number of times. This can be done with a while statement. For example to execute a statement n times could be implemented as follows:
set count to zero. while count is less than n { statement. increment count. }There are several things that the programmer has to get right here, the initial value of count, the condition and remembering to increment count inside the loop body. It would be simpler to use a construct like:
repeat n times { statement. }Many loops fall into this simple category. The following problem identifies a related form of repetition control structure.
Write a program to enter a value for n and output a table of the squares of the numbers from 1 to n.An algorithm to solve this problem could be written as follows:
for i taking values from 1 to n do { output i and i squared. take a new line. }It is normal in the forms `repeat n times' and `for i taking values from start to finish' to not execute the body of the loop if n is zero or if the start value is greater than the finish value.
The most basic of repetition control structures is the while control structure since all the others can be simulated by it. However the others are useful in some cases, particularly the for control structure. They all have equivalents in C++.