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 or equal to 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:
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
for J in reverse 10 .. 1 looprepeats 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
If you wanted to repeat something exactly ten times, which iteration construct would be the most straightforward?
|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/s5sf.htm".