Section 5.3 - Simple Loops

Ada has a number of `looping constructs' for situations where something must repeat over and over again. The simplest looping construct just repeats `forever'. A simple loop simply begins with the phrase ``loop'', has statements to repeat, and ends with ``end loop;''. Here's an example of a procedure body that, when run, repeatedly prints the same message over and over again:

with Text_IO; use Text_IO;
procedure Forever is
  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;
 exit when X = 0;
  Put(X * X);
 end loop;
end Print_Squares;


What will A's final value be?

A := 1;
 A := A + 1;
 exit when A > 3;
end loop;
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 5 outline

David A. Wheeler (

The master copy of this file is at "".