with Text_IO; use Text_IO; procedure Forever is begin loop Put_Line("Hello again!"); end loop; end Forever;
A loop can be terminated through an ``exit'' or an ``exit when'' clause (similar to C's break statement). An `exit' causes an immediate exiting of the innermost loop. An `exit when' clause causes exiting of the innermost loop only if the following condition is true.
The `exit when' clause is particularly useful in circumstances where you must do some action(s) before you can figure out if the loop has to stop or not. These are called ``loop-and-a-half'' constructs - you start with "loop", perform calculations to determine if the loop should stop, use an `exit when' to exit on that condition, and then work on the result.
Here's an example of a loop-and-a-half. This program reads in a list of numbers and prints out their squares, but stops (without printing) when it reads in the number `0':
with Text_IO, Ada.Integer_Text_IO; use Text_IO, Ada.Integer_Text_IO; procedure Print_Squares is X : Integer; begin loop Get(X); exit when X = 0; Put(X * X); New_Line; end loop; end Print_Squares;
What will A's final value be?
A := 1; loop A := A + 1; exit when A > 3; end loop;
|Go back to the previous section||Skip to the next section||Go up to lesson 5 outline|
David A. Wheeler (firstname.lastname@example.org)
The master copy of this file is at
The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s5s3.htm".