ZetCode

Pascal recursion

last modified November 18, 2026 Free Pascal 3.2.2

A recursive routine calls itself with a smaller problem until it reaches a case that can be answered directly. The direct case is the base case, and the call that reduces the problem is the recursive step. Recursion is the natural way to express factorials, tree traversals, divide-and-conquer algorithms, and puzzles such as the Towers of Hanoi. This article writes several recursive functions, measures the cost of naive recursion, adds memoization, and shows how recursion walks arrays and strings.

Factorial

The factorial of n is the product of all integers from 1 to n. The recursive definition is n! = n × (n − 1)!, with 0! and 1! equal to 1. The function below translates that definition directly into Pascal.

factorial.pas
program factorial;
{$mode objfpc}{$H+}

function Factorial(N: Integer): Int64;
begin
  if N <= 1 then
    Result := 1
  else
    Result := N * Factorial(N - 1);
end;

var
  I: Integer;

begin
  for I := 0 to 10 do
    WriteLn(I, '! = ', Factorial(I));
  WriteLn('20! = ', Factorial(20));
end.

The base case N <= 1 stops the recursion. Each call multiplies its argument by the result of the next smaller call, and the multiplications happen on the way back up the call stack. The result type is Int64 because 13! already exceeds the range of a 32-bit integer; 20! is the largest factorial that fits in a signed 64-bit value.

$ fpc -gl factorial.pas
$ ./factorial
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
20! = 2432902008176640000

Fibonacci and the cost of naive recursion

The Fibonacci sequence starts with 0 and 1, and every later value is the sum of the two before it. The recursive definition is short, but it recomputes the same values many times: Fib(5) calls Fib(3) twice and Fib(2) three times. The program counts the calls to make the cost visible.

fib.pas
program fib;
{$mode objfpc}{$H+}

var
  Calls: Int64;

function Fib(N: Integer): Int64;
begin
  Inc(Calls);
  if N < 2 then
    Result := N
  else
    Result := Fib(N - 1) + Fib(N - 2);
end;

var
  I: Integer;

begin
  for I := 0 to 10 do
  begin
    Calls := 0;
    WriteLn('Fib(', I, ') = ', Fib(I), ', calls = ', Calls);
  end;
end.

The number of calls grows exponentially. Fib(10) needs 177 calls for a result of 55, and Fib(40) would need more than three hundred million. The recursive definition is mathematically clear but computationally wasteful because the same subproblem is solved again and again.

$ fpc -gl fib.pas
$ ./fib
Fib(0) = 0, calls = 1
Fib(1) = 1, calls = 1
Fib(2) = 1, calls = 3
Fib(3) = 2, calls = 5
Fib(4) = 3, calls = 9
Fib(5) = 5, calls = 15
Fib(6) = 8, calls = 25
Fib(7) = 13, calls = 41
Fib(8) = 21, calls = 67
Fib(9) = 34, calls = 109
Fib(10) = 55, calls = 177

Memoization

Memoization stores each computed result and returns it on the next request. The function keeps an array of cached values, initialized to -1, and fills an entry the first time a value is calculated. Because a value is computed only once, the exponential tree of calls collapses into a linear chain.

memo.pas
program memo;
{$mode objfpc}{$H+}

const
  MaxN = 90;

var
  Cache: array[0..MaxN] of Int64;
  Hits: Integer;

function Fib(N: Integer): Int64;
begin
  if Cache[N] >= 0 then
  begin
    Inc(Hits);
    Result := Cache[N];
  end
  else if N < 2 then
  begin
    Cache[N] := N;
    Result := N;
  end
  else
  begin
    Result := Fib(N - 1) + Fib(N - 2);
    Cache[N] := Result;
  end;
end;

var
  I: Integer;

begin
  for I := 0 to MaxN do
    Cache[I] := -1;
  Hits := 0;
  WriteLn('Fib(50)  = ', Fib(50));
  WriteLn('Fib(90)  = ', Fib(90));
  WriteLn('cache hits = ', Hits);
end.

Fib(90) is 2880067194370816120, which fits in an Int64. The second call reuses the values computed by the first, so the whole program performs about ninety calculations instead of an astronomical number. The cache is indexed by N, which is why MaxN must cover the largest argument; a memoized function with a sparse or unbounded argument range would use a dictionary instead.

$ fpc -gl memo.pas
$ ./memo
Fib(50)  = 12586269025
Fib(90)  = 2880067194370816120
cache hits = 89

Towers of Hanoi

The Towers of Hanoi puzzle has three pegs and a stack of disks of different sizes. The goal is to move the whole stack from one peg to another, moving one disk at a time and never placing a larger disk on a smaller one. The recursive solution moves the top n − 1 disks out of the way, moves the largest disk, and then moves the smaller stack onto it.

hanoi.pas
program hanoi;
{$mode objfpc}{$H+}

var
  Moves: Integer;

procedure MoveDisks(N: Integer; const FromPeg, ToPeg, ViaPeg: string);
begin
  if N = 0 then
    Exit;
  MoveDisks(N - 1, FromPeg, ViaPeg, ToPeg);
  Inc(Moves);
  WriteLn('move disk ', N, ' from ', FromPeg, ' to ', ToPeg);
  MoveDisks(N - 1, ViaPeg, ToPeg, FromPeg);
end;

begin
  Moves := 0;
  MoveDisks(3, 'A', 'C', 'B');
  WriteLn('moves = ', Moves);
end.

Three disks need seven moves, which is 23 − 1. In general the minimum number of moves is 2n − 1, so the puzzle grows exponentially even though the algorithm is only a few lines. The parameters name the source peg, the destination peg, and the spare peg, which makes the recursive calls readable.

$ fpc -gl hanoi.pas
$ ./hanoi
move disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B
move disk 3 from A to C
move disk 1 from B to A
move disk 2 from B to C
move disk 1 from A to C
moves = 7

Euclid's algorithm

The greatest common divisor of two integers can be found by repeated remainders: Gcd(A, B) is Gcd(B, A mod B), and the process stops when the second argument becomes zero. The recursion depth is logarithmic, so the algorithm is fast even for large inputs.

gcd.pas
program gcd;
{$mode objfpc}{$H+}

function Gcd(A, B: Integer): Integer;
begin
  if B = 0 then
    Result := A
  else
    Result := Gcd(B, A mod B);
end;

function Lcm(A, B: Integer): Integer;
begin
  Result := A * B div Gcd(A, B);
end;

begin
  WriteLn('Gcd(48, 18)  = ', Gcd(48, 18));
  WriteLn('Gcd(17, 5)   = ', Gcd(17, 5));
  WriteLn('Gcd(100, 75) = ', Gcd(100, 75));
  WriteLn('Lcm(4, 6)    = ', Lcm(4, 6));
end.

Gcd(48, 18) reduces to Gcd(18, 12), then Gcd(12, 6), and finally Gcd(6, 0), which returns 6. The least common multiple is the product divided by the greatest common divisor, so Lcm(4, 6) is 24 divided by 2, which is 12.

$ fpc -gl gcd.pas
$ ./gcd
Gcd(48, 18)  = 6
Gcd(17, 5)   = 1
Gcd(100, 75) = 25
Lcm(4, 6)    = 12

Ackermann's function

Ackermann's function is a classic example of recursion that is not primitive recursive: it grows faster than any function defined by bounded loops. The definition has two recursive branches, and the inner call can make the outer argument larger. Small arguments are enough to see the growth.

ackermann.pas
program ackermann;
{$mode objfpc}{$H+}

function Ack(M, N: Integer): Integer;
begin
  if M = 0 then
    Result := N + 1
  else if N = 0 then
    Result := Ack(M - 1, 1)
  else
    Result := Ack(M - 1, Ack(M, N - 1));
end;

begin
  WriteLn('Ack(0, 0) = ', Ack(0, 0));
  WriteLn('Ack(1, 2) = ', Ack(1, 2));
  WriteLn('Ack(2, 3) = ', Ack(2, 3));
  WriteLn('Ack(3, 3) = ', Ack(3, 3));
end.

Ack(3, 3) is 61, and Ack(4, 1) is already 65533. The function is useful as a stress test for compilers and for the call stack, not as a practical algorithm. It also shows that a recursive definition can be valid and terminate while still being far too expensive for everyday use.

$ fpc -gl ackermann.pas
$ ./ackermann
Ack(0, 0) = 1
Ack(1, 2) = 4
Ack(2, 3) = 9
Ack(3, 3) = 61

Recursion over arrays and strings

Recursion is not limited to numbers. An array can be summed by adding the current element to the sum of the rest, and a string can be checked for palindrome by comparing the ends and recursing on the inside. Both functions carry an index or a pair of indices that shrinks with each call.

arrayrec.pas
program arrayrec;
{$mode objfpc}{$H+}

function Sum(const A: array of Integer; Index: Integer): Integer;
begin
  if Index >= Length(A) then
    Result := 0
  else
    Result := A[Index] + Sum(A, Index + 1);
end;

function IsPalindrome(const S: string; Left, Right: Integer): Boolean;
begin
  if Left >= Right then
    Result := True
  else if S[Left] <> S[Right] then
    Result := False
  else
    Result := IsPalindrome(S, Left + 1, Right - 1);
end;

var
  Numbers: array[1..6] of Integer = (4, 8, 15, 16, 23, 42);

begin
  WriteLn('sum = ', Sum(Numbers, 0));
  WriteLn('racecar: ', IsPalindrome('racecar', 1, 7));
  WriteLn('pascal:  ', IsPalindrome('pascal', 1, 6));
  WriteLn('abba:    ', IsPalindrome('abba', 1, 4));
end.

Sum starts at index 0 and adds one element per call; the open array parameter accepts both the static array and a dynamic array. The palindrome check returns true when the indices meet, false as soon as the characters differ, and otherwise moves both indices inward. String indices in Pascal start at 1, so the initial right index is Length(S).

$ fpc -gl arrayrec.pas
$ ./arrayrec
sum = 108
racecar: TRUE
pascal:  FALSE
abba:    TRUE

When to use recursion

Recursion is the clearest choice for structures that are themselves recursive: trees, nested expressions, divide-and-conquer algorithms, and backtracking searches. It is a poor choice when the recursion depth can grow with the input, because every call consumes stack space. A loop is usually better for a simple sequence, and memoization or dynamic programming is better when the same subproblems repeat.

Free Pascal does not optimize tail calls by default, so a function that calls itself as its last action still uses a stack frame per call. The binary trees article relies on recursion for its traversals, and the sorting article uses it for quick sort and merge sort. When a recursive version is too deep, rewrite it with an explicit stack from the stacks and queues article.

Next steps

The sorting article applies recursion to quick sort and merge sort, and the binary trees article uses it for insertion, traversal, and deletion. The procedures article explains the parameter passing that these functions rely on.

Source

Free Pascal Reference guide

Recursion on Wikipedia

In this article we have written recursive factorial and Fibonacci functions, added memoization, solved the Towers of Hanoi, implemented Euclid's algorithm and Ackermann's function, and recursed over arrays and strings. The series continues with sorting in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.