Section 5.3 - Loop Iteration Schemes

There are two other common styles of loops that are directly supported in Ada: while loops and for loops. While and for loops are called `iteration schemes'; they are loops with information prepended to them on the kind of looping scheme desired.

The while loop is particularly easy; write a normal loop block, and put in front of the block the keyword ``while'' and a condition. Here is an example of a loop that, while N is less than 20, it prints N and then adds one to it:

 while N < 20
 loop
  Put(N);
  N := N + 1;
 end loop;

The for loop is similar, starting with the keyword ``for''. A for loop assigns a local loop parameter a lower value. It then repeatedly checks if the loop parameter is less than the higher value, and if so it executes a sequence of statements and then adds one to the loop parameter. Here's an example of a loop that prints "Hello" 20 times:

 for Count in 1 .. 20
 loop
   Put_Line("Hello");
 end loop;

There are some key points about for loops that need mentioning:

  1. The variable named in the `for' loop is a local variable visible only in the statements inside it, and it cannot be modified by the statements inside (you can exit a for loop, using the exit statement we've already seen).
  2. Normally a loop always adds one. The reverse order can be requested by using the keyword `reverse' after the keyword `in'. In this case the loop value starts with the upper bound (given second) and decrements until it is less than the lower bound (given first).

The construct:

  for J in 10 .. 1 loop

repeats zero times because 10 is always greater than 1.

One warning - the construct

  for J in reverse 10 .. 1 loop
repeats zero times as well; Ada considers 10 .. 1 an empty list. What you probably want instead is:
  for J in reverse 1 .. 10 loop

Quiz:


If you wanted to repeat something exactly ten times, which iteration construct would be the most straightforward?
  1. While loop.
  2. For loop.
  3. A loop without an iteration scheme.

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to the outline of lesson 5

David A. Wheeler (wheeler@ida.org)