Sometimes it is more natural to test part way through, or at end, of executing statements in the loop body.
loop statements_1; exit when test; statements_2; end loop;
While:
while test loop statements; end loop;
general:
loop exit when not test; statements; end loop;
loop 2. read a value from user 3. if end value entered, leave the loop 4. do something with value end of loop
Another example is summing numbers up to (but excluding) an exit value:
while:
PUT("Enter an integer (-1 to exit): "); GET(j); SKIP_LINE; tot := 0; while j /= -1 loop tot := tot + j; PUT("Enter an integer (-1 to exit): "); GET(j); SKIP_LINE; end loop; PUT("Total is "); PUT(tot); NEW_LINE;
general:
tot := 0; loop PUT("Enter an integer (-1 to exit): "); GET(j); SKIP_LINE; exit when (j = -1); tot := tot + j; end loop; PUT("Total is "); PUT(tot); NEW_LINE;
Note that statements need to be duplicated when using the while loop.
loop statement(s); exit when test; end loop;
Eg read until an acceptable value entered:
while:
j := -1; while (j < 0) loop PUT("Enter positive integer: "); GET(j); SKIP_LINE; end loop;
general:
loop PUT("Enter positive integer: "); GET(j); SKIP_LINE; exit when j >= 0; end loop;
The code in the general loop is easier to understand.