Previous topic |
Next topic |
Ada Home Page |
Index
Loop control
There are three aspects to loop control for any loop:
- initialisation of loop parameter(s)
- automatic in a for loop
- before a while loop
- before a general loop, or in the
statements before the exit test
- test
- automatic in a for loop
- while: test for continuation
- general: test for termination
- update loop parameter
- not allowed inside for loop
- must update inside indefinite loop
Loop Design
Choose the appropriate loop statement, and then specify the three
aspects to loop control.
Approaches to loop design:
- analyse the individual application
- recognise standard situations, use standard loops for those situations
(eg
sentinel-controlled loops,
flag-controlled loops)
- use loop templates
- definite or indefinite?
- when to test for termination?
- what is appropriate initialisation etc?
When an unknown number of data items are to be processed, some way to
recognise the end of the data is needed.
One solution is to define a sentinel value
- a unique value that indicates end-of-data
- it cannot be a value that could occur as data
Code template:
sentinel : constant := ???;
loop
read (item);
exit when item = sentinel;
process the item;
end loop;
Example: add integers that the user enters, up to but not including -1 for
end of data
tot := 0;
loop
PUT("Enter an integer (-1 to exit): ");
GET(j); SKIP_LINE;
exit when (j = -1);
tot := tot + j;
end loop;
A flag is a boolean variable, used to indicate whether or not a
desired situation has occurred
- a value of FALSE indicates that the desired event has not yet occurred
- TRUE indicates that it has occurred
Code template:
flag : BOOLEAN;
flag := FALSE;
while not flag loop
do some processing;
if desired event has happened then
flag := TRUE;
end if;
do some processing;
end loop;
Example: read characters until a digit is typed
DigitRead := FALSE;
while not DigitRead loop
get (c);
if (c >= '0') and (c <= '9') then
DigitRead := TRUE;
end if;
end loop;
Previous topic |
Next topic |
Ada Home Page |
Index
c-lokan@adfa.oz.au / 14 Feb 96