Recursion in Pascal

Our example demonstrates recursive functions in Pascal. Here’s a classic example of factorial calculation using recursion.

program RecursionExample;

uses
  SysUtils;

function Fact(n: Integer): Integer;
begin
  if n = 0 then
    Result := 1
  else
    Result := n * Fact(n - 1);
end;

function Fib(n: Integer): Integer;
begin
  if n < 2 then
    Result := n
  else
    Result := Fib(n - 1) + Fib(n - 2);
end;

begin
  WriteLn(Fact(7));
  WriteLn(Fib(7));
end.

This Fact function calls itself until it reaches the base case of Fact(0).

In the begin block, we call our recursive functions and print their results.

Pascal doesn’t have closures like some modern languages, so we’ve implemented the Fibonacci function as a regular recursive function instead.

To run this program, save it as recursion.pas and compile it using a Pascal compiler like Free Pascal:

$ fpc recursion.pas
$ ./recursion
5040
13

The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).

Recursive functions can be powerful but should be used carefully, as deep recursion can lead to stack overflow errors. In many cases, an iterative solution might be more efficient.