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:
The construct:
for J in 10 .. 1 loop
One warning - the construct
for J in reverse 10 .. 1 looprepeats zero times as well; Ada considers 10 .. 1 an empty list. What you probably want instead is:
for J in reverse 1 .. 10 loop
Go back to the previous section
Go up to the outline of lesson 5
David A. Wheeler (wheeler@ida.org)