Computer Science Canada

[Ada-tut] Control Structures: Loops

Author:  wtd [ Mon Oct 11, 2004 9:41 pm ]
Post subject:  [Ada-tut] Control Structures: Loops

Background

As most should be aware, loops are essential to programming, since there are times when it's necessary to repeat the same code several times.

For those with Turing experience, Ada95 loops will look rather familiar.

The most basic loop

Let's say we want a program which repeatedly prints out "Hello, world!"

code:
with Ada.Text_IO; use Ada.Text_IO;
procedure Simple_Program is
begin
   loop
      Put_Line("Hello, world!");
   end loop;
end Simple_Program;


But how do I make it stop?

Of course this offers no exit condition. It'll keep on going until the heat death of the universe if it's allowed.

So let's use the "exit when" syntax to get out after 5 times.

code:
with Ada.Text_IO; use Ada.Text_IO;
procedure Simple_Program is
   Counter : Integer := 1;
begin
   loop
      Put_Line("Hello, world!");
      Counter := Counter + 1;
      exit when Counter > 5;
   end loop;
end Simple_Program;


Ada95 also provides "exit" for breaking out of a loop at any time.

While loops

So we've stopped our loop after 5 turns. There has to be an easier way, though.

code:
with Ada.Text_IO; use Ada.Text_IO;
procedure Simple_Program is
   Counter : Integer := 1;
begin
   while Counter <= 5
   loop
      Put_Line("Hello, world!");
      Counter := Counter + 1;
   end loop;
end Simple_Program;


For loops

But for such a simple example, it gets even easier.

code:
with Ada.Text_IO; use Ada.Text_IO;
procedure Simple_Program is
begin
   for Counter in 1 .. 5
   loop
      Put_Line("Hello, world!");
   end loop;
end Simple_Program;


Reversed for loops

The problem with this is that we can go from 1 to 5 with the range operator, but we can't go from 5 to 1 with it. Instead we have to explicitly use the "reverse" keyword.

So let's count down from 10 to 1.

code:
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Simple_Program is
begin
   for Counter in reverse 1 .. 10
   loop
      Put(Counter);
   end loop;
end Simple_Program;


: