For in Ada
On this page
Different Types of for
Loops in Ada
Ada’s looping constructs offer a versatile range of loop types similar in functionality. Here’s how you can achieve different types of looping constructs in Ada.
Basic Loop with a Single Condition
The most basic loop type uses a condition to control the repetition.
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
declare
I : Integer := 1;
begin
while I <= 3 loop
Put_Line(Integer'Image(I));
I := I + 1;
end loop;
end;
end Main;
Classic Initial/Condition/Iteration Loop
This type of loop explicitly initializes the loop variable, checks the condition, and updates the variable after each iteration.
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
for J in 0 .. 2 loop
Put_Line(Integer'Image(J));
end loop;
end Main;
Iteration Using for
Loop Range
Ada’s for
loop can also iterate over a range with ease which is similar to iteration using range
.
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
for I in 0 .. 2 loop
Put_Line("range" & Integer'Image(I));
end loop;
end Main;
Infinite Loop with break
Equivalent
A loop without a condition will repeat indefinitely until it encounters an exit statement to break out of the loop (equivalent to break
).
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
loop
Put_Line("loop");
exit;
end loop;
end Main;
Using continue
Equivalent in a Loop
In Ada, the concept of continue
is achieved using exit when
followed by the condition you’d like to skip.
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
for N in 0 .. 5 loop
if N mod 2 = 0 then
-- Continue to the next iteration
null;
else
Put_Line(Integer'Image(N));
end if;
end loop;
end Main;
Running the Ada Program
To run an Ada program, you need to compile the .adb
file yielding an executable which can then be run.
$ gnatmake main.adb
$ ./main
Expected output for running the compiled program:
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
Gaining familiarity with these looping constructs will help in writing efficient Ada programs. In future examples, we’ll explore more detailed structures and functionalities in the language.