Ada recursion
last modified November 23, 2026
A recursive subprogram calls itself on a smaller piece of the same problem. Every recursion needs a base case that returns without another call, and every recursive step must move toward that base case. This article starts with factorial, walks through arrays, compares naive and memoised Fibonacci, solves the Towers of Hanoi, measures how deep the stack can go, and generates permutations by backtracking.
A recursive function
The factorial of a natural number is the product of all numbers from one to it,
and zero factorial is one by definition. Fact returns 1 for the
base case and otherwise multiplies N by the factorial of
N - 1. Each call has its own copy of N.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Factorial is
function Fact (N : Natural) return Natural is
begin
if N = 0 then
return 1;
else
return N * Fact (N - 1);
end if;
end Fact;
begin
for I in 0 .. 6 loop
Put_Line (Integer'Image (I) & "! =" & Integer'Image (Fact (I)));
end loop;
end Factorial;
The calls go down from 6 to 0 and the multiplications happen on the way back
up: the innermost call returns 1, then 1 is multiplied by 1, then by 2, and so
on. Fact returns Natural, so the result must fit in
the 32-bit integer range; 13! is already 6227020800, which is too large, and
the program would raise Constraint_Error.
$ gnatmake -gnat2022 -gnatwa factorial.adb $ ./factorial 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720
Recursion over an array
An array can be processed by recursion over its index range. Sum
adds the element at First to the sum of the rest, and stops when
the range is empty. Largest works from the other end, comparing the
last element with the largest of the prefix.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Array_Recursion is
type Numbers is array (Positive range <>) of Integer;
Data : constant Numbers := [4, 9, 2, 7, 5, 8];
function Sum (A : Numbers; First, Last : Positive) return Integer is
begin
if First > Last then
return 0;
else
return A (First) + Sum (A, First + 1, Last);
end if;
end Sum;
function Largest (A : Numbers; Last : Positive) return Integer is
begin
if Last = A'First then
return A (Last);
else
return Integer'Max (A (Last), Largest (A, Last - 1));
end if;
end Largest;
begin
Put_Line ("sum =" & Integer'Image (Sum (Data, Data'First, Data'Last)));
Put_Line ("largest =" & Integer'Image (Largest (Data, Data'Last)));
end Array_Recursion;
Sum passes the shrinking range explicitly, which makes the base
case easy to see: an empty range contributes nothing. Largest
keeps the upper bound and uses A'First as its stopping point. Both
functions are recursive even though neither changes the array; the recursion is
over the indices.
$ gnatmake -gnat2022 -gnatwa array_recursion.adb $ ./array_recursion sum = 35 largest = 9
Two recursive calls: Fibonacci
The Fibonacci numbers start 0, 1, 1, 2, 3, 5, and each later value is the sum
of the two before it. The direct recursive translation makes two calls per
step, which builds a large call tree: most subproblems are computed again and
again. A counter shows how much work Fib (20) really does.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Fibonacci is
Calls : Natural := 0;
function Fib (N : Natural) return Natural is
begin
Calls := Calls + 1;
if N < 2 then
return N;
else
return Fib (N - 1) + Fib (N - 2);
end if;
end Fib;
begin
Put_Line ("Fib (20) =" & Integer'Image (Fib (20)));
Put_Line ("calls =" & Integer'Image (Calls));
end Fibonacci;
Twenty-one thousand calls produce a value that a loop could compute in twenty steps. The count grows exponentially because the same values reappear in different branches of the tree. The result is still correct, but the method is unsuitable beyond small inputs.
$ gnatmake -gnat2022 -gnatwa fibonacci.adb $ ./fibonacci Fib (20) = 6765 calls = 21891
Memoisation
Memoisation stores each answer the first time it is computed. The
Known array records which entries of Results are
valid, so a repeated call returns immediately. The same Fib
function now computes Fib (40) with only 79 calls instead of
millions.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Memo_Fib is
Max : constant := 90;
type Result_Array is array (Natural range 0 .. Max) of Natural;
Results : Result_Array := [others => 0];
Known : array (Natural range 0 .. Max) of Boolean := [others => False];
Calls : Natural := 0;
function Fib (N : Natural) return Natural is
begin
Calls := Calls + 1;
if Known (N) then
return Results (N);
end if;
if N < 2 then
Results (N) := N;
else
Results (N) := Fib (N - 1) + Fib (N - 2);
end if;
Known (N) := True;
return Results (N);
end Fib;
begin
Put_Line ("Fib (40) =" & Integer'Image (Fib (40)));
Put_Line ("calls =" & Integer'Image (Calls));
end Memo_Fib;
The table turns an exponential algorithm into a linear one, at the cost of
memory proportional to the largest argument. The array is indexed by
Natural, so the bounds are 0 to 90, and the initial aggregate
fills it with zeros and False. Values above Fib (46)
no longer fit in Integer on this platform even though the table
has room for larger indices.
$ gnatmake -gnat2022 -gnatwa memo_fib.adb $ ./memo_fib Fib (40) = 102334155 calls = 79
Towers of Hanoi
The Towers of Hanoi puzzle has three pegs and a stack of disks of different
sizes. Only one disk may move at a time, and a larger disk may never be placed
on a smaller one. To move N disks from From to
To, first move the top N - 1 disks to the spare peg,
move the largest disk, and then move the smaller stack onto it.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Hanoi is
Moves : Natural := 0;
procedure Move (N : Positive; From, To, Via : Character) is
begin
if N = 1 then
Moves := Moves + 1;
Put_Line ("move disk 1 from " & From & " to " & To);
else
Move (N - 1, From, Via, To);
Moves := Moves + 1;
Put_Line ("move disk" & Integer'Image (N) & " from " & From & " to " & To);
Move (N - 1, Via, To, From);
end if;
end Move;
begin
Move (4, 'A', 'C', 'B');
Put_Line ("moves =" & Integer'Image (Moves));
end Hanoi;
The two recursive calls exchange the roles of the pegs. With four disks the
program prints fifteen moves, which is 2 ** 4 - 1. Each additional
disk doubles the work, so the puzzle is a compact demonstration of exponential
growth even though the code is only a few lines.
$ gnatmake -gnat2022 -gnatwa hanoi.adb $ ./hanoi move disk 1 from A to B move disk 2 from A to C move disk 1 from B to C move disk 3 from A to B move disk 1 from C to A move disk 2 from C to B move disk 1 from A to B move disk 4 from A to C move disk 1 from B to C move disk 2 from B to A move disk 1 from C to A move disk 3 from B to C move disk 1 from A to B move disk 2 from A to C move disk 1 from B to C moves = 15
How deep can recursion go?
Every active call keeps a frame on the run-time stack, so a recursion that never reaches its base case eventually exhausts the stack. The following function is not tail recursive, because the addition happens after the call returns, so the frames cannot be reused. One million levels are more than the default stack allows.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Deep_Recursion is
function Down (N : Natural) return Natural is
begin
if N = 0 then
return 0;
end if;
return Down (N - 1) + 1;
end Down;
begin
Put_Line ("depth =" & Integer'Image (Down (1_000_000)));
exception
when Storage_Error =>
Put_Line ("stack exhausted");
end Deep_Recursion;
GNAT raises Storage_Error when the stack cannot grow further, and
the handler prints its message instead of letting the program die. The process
still exits with status 0 because the exception was handled. A loop would use
constant space, and a compiler is not required to turn this recursion into one.
$ gnatmake -gnat2022 -gnatwa deep_recursion.adb $ ./deep_recursion stack exhausted
An applied example: permutations
Backtracking is recursion that undoes its choice before trying the next one.
Generate fixes the element at Start, recursively
arranges the rest, and then swaps the element back. When Start is
the last index, the array is a complete permutation and is printed.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Permutations is
type Letters is array (Positive range <>) of Character;
Data : Letters := ['A', 'B', 'C'];
procedure Swap (I, J : Positive) is
Temp : constant Character := Data (I);
begin
Data (I) := Data (J);
Data (J) := Temp;
end Swap;
procedure Generate (Start : Positive) is
begin
if Start = Data'Last then
Put_Line (String (Data));
else
for I in Start .. Data'Last loop
Swap (Start, I);
Generate (Start + 1);
Swap (Start, I);
end loop;
end if;
end Generate;
begin
Generate (Data'First);
end Permutations;
The second Swap is what makes the algorithm correct: without it,
each branch would start from the previous permutation instead of the original
order. The output is not alphabetical, because the order depends on which
element is moved into each position. String (Data) converts the
character array to a string for printing.
$ gnatmake -gnat2022 -gnatwa permutations.adb $ ./permutations ABC ACB BAC BCA CBA CAB
Next steps
The next article applies recursion and iteration to sorting: insertion sort, quicksort, merge sort, and the generic array sort from the standard container library. The procedures and functions article introduces the subprogram syntax that every example here uses.
Source
In this article we have written recursive functions with base cases, recursed
over array ranges, built the call tree of Fibonacci, replaced repeated work with
a memo table, solved the Towers of Hanoi, exhausted the stack and caught
Storage_Error, and generated permutations by backtracking. The
arrays and exceptions
articles explain the array parameters and the handler used along the way.
Author
List all Ada tutorials.