Next topic |
Ada Home Page |
Index
Loop statements
Another basic construct in programming is iteration (along with
sequence and selection).
Iteration is the process of repeating a set of actions some number
of times.
Definite iteration
is where the set of actions is performed a known
number of times. The number might be determined by
the program specification, or it might not be known until the program is
executing, just before starting the iteration.
Ada provides the FOR statement for definite iteration.
Indefinite iteration
is where the set of actions is performed a
unknown number of times. The number is determined
during execution of the loop.
Ada provides the WHILE statement
and general LOOP statement
for indefinite iteration.
With several types of loops available, we need to use most appropriate
for any given situation.
WHILE vs FOR
The while loop is most general
- used for indefinite iteration
- by setting value of variables used in the test, can be made to execute at
least once, or maybe never
For loops:
- used for definite iteration (know number of times to run before loop)
- can be replaced by a while loop, but usually not as elegant
WHILE vs General LOOP
It is easier to reason with while loops than with general loops.
While:
- obvious where loop exits
- can guarantee that the entry test has been passed when executing the
statements of the loop body
General loop:
- sometimes code is simpler
- there is no guarantee when executing the statements before the test (this
may be the first time through the loop)
Which loop statement to use?
-
For definite loops, use for
- automated control
- tells reader that number of iterations known
-
For indefinite loops, where pre-test is natural, use while
-
For other indefinite loops, use general loop
Usually prefer for and while.
Next topic |
Ada Home Page |
Index
c-lokan@adfa.oz.au / 13 Feb 96