Section 5.4 - 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, as you saw in the previous section, and put in front of the block the keyword ``while'' and a condition. A while loop repeatedly executes the statements in the loop as long as the while condition is true. 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).

Both ``while'' and ``for'' loops check their conditions before executing each loop. That means that the loop can conceivably execute "zero" times if the loop condition starts as false. This does create a trap for beginning Ada programmers, though. The construct:

  for J in 10 .. 1 loop

repeats zero times (i.e. it never executes the loop contents) because 10 is always greater than 1.

The construct

  for J in reverse 10 .. 1 loop
repeats zero times as well; Ada considers 10 .. 1 an empty list, and doing nothing in reverse order still does nothing. 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 lesson 5 outline

David A. Wheeler (dwheeler@ida.org)