Previous topic |
Next topic |
Ada Home Page |
Index
While statement
Indefinite iteration is where the set of actions is performed an
unknown number of times. In Ada, a WHILE statement is usually used for
indefinite iteration.
We saw an example
using a while loop, in the initial introduction to Ada.
Statement form:
while test loop
statement(s);
end loop;
While loops may be designed as a
repeat structure, to execute at least once
- example (to ensure you have a positive value of j)
j := -1;
while (j < 0) loop
PUT("Enter positive j: "); GET(j); SKIP_LINE;
end loop;
A while loop may not execute at all
- example (to test when finished)
tot := 0;
PUT("Enter j (-1 to exit): "); GET(j); SKIP_LINE;
while (j /= -1) loop
tot := tot + j;
PUT("Enter j (-1 to exit): "); GET(j); SKIP_LINE;
end loop;
PUT("Total is "); PUT(tot); NEW_LINE;
An example program
shows the use of a while loop when a user is being asked to answer
'Y' or 'N' to a question. The loop executes continually until a
suitable value is typed by the user.
Rules for while statements
- test is an expression which evaluates as either true or false (as
in if statements)
- the statement(s) may be any Ada statements
- the entire while structure (from while to end loop) is a single
Ada statement, terminated by a ;
Style Rules for while statements
- statement(s) inside the while are indented by a constant amount
- the end loop is required, and should be at the same indent as the
corresponding while
Semantics of while statement
while != if
Previous topic |
Next topic |
Ada Home Page |
Index
c-lokan@adfa.oz.au / 13 Feb 96