ZetCode

Modula-2 recursion

last modified November 27, 2026 Modula-2

A procedure is recursive when it calls itself. It solves a problem by reducing it to a smaller problem of the same kind, until the problem is small enough to answer directly. That smallest case is the base case, and every recursive procedure needs one.

The procedures article showed that a Modula-2 procedure may call itself and computed the greatest common divisor with Euclid's algorithm. This article looks at recursion more closely. The examples use the ISO library and are compiled with -fiso, as in the console output article.

A procedure that calls itself

The factorial of n is the product 1 × 2 × … × n, and the factorial of 0 is 1. Since n! = n × (n − 1)!, the definition translates directly into a recursive procedure.

factorial.mod
MODULE factorial;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  k: CARDINAL;

PROCEDURE Fact(n: CARDINAL): CARDINAL;
BEGIN
  IF n = 0 THEN
    RETURN 1
  END;
  RETURN n * Fact(n - 1)
END Fact;

BEGIN
  FOR k := 0 TO 8 DO
    WriteCard(k, 2); WriteString("! = ");
    WriteCard(Fact(k), 0); WriteLn
  END
END factorial.

Fact returns 1 for the base case 0. For any other value it multiplies n by the factorial of n - 1, which is a smaller problem of the same kind. Each call moves one step closer to the base case, so the recursion ends.

$ gm2 -fiso factorial.mod -o factorial
$ ./factorial
 0! = 1
 1! = 1
 2! = 2
 3! = 6
 4! = 24
 5! = 120
 6! = 720
 7! = 5040
 8! = 40320

How the calls unfold

Every call of a procedure gets its own copy of the parameters and local variables. The next program prints a line when Fact starts and when it returns, indented by the depth of the call.

trace.mod
MODULE trace;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  r: CARDINAL;

PROCEDURE Indent(depth: CARDINAL);
VAR
  i: CARDINAL;
BEGIN
  FOR i := 1 TO depth DO
    WriteString("  ")
  END
END Indent;

PROCEDURE Fact(n, depth: CARDINAL): CARDINAL;
VAR
  result: CARDINAL;
BEGIN
  Indent(depth);
  WriteString("Fact("); WriteCard(n, 0); WriteString(")"); WriteLn;
  IF n = 0 THEN
    result := 1
  ELSE
    result := n * Fact(n - 1, depth + 1)
  END;
  Indent(depth);
  WriteString("returns "); WriteCard(result, 0); WriteLn;
  RETURN result
END Fact;

BEGIN
  r := Fact(4, 0)
END trace.

The extra parameter depth grows by one with every call, and Indent writes two spaces per level. The calls go down to Fact(0) first; only then are the multiplications done, on the way back up. While Fact(0) runs, five calls are active at once, each with its own n and result.

$ gm2 -fiso trace.mod -o trace
$ ./trace
Fact(4)
  Fact(3)
    Fact(2)
      Fact(1)
        Fact(0)
        returns 1
      returns 1
    returns 2
  returns 6
returns 24

The cost of naive recursion

The Fibonacci numbers start with 0 and 1, and each next number is the sum of the two before it. The definition is recursive, but a direct translation is slow. The program counts the calls in a global variable.

fibonacci.mod
MODULE fibonacci;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  calls, k, f: CARDINAL;

PROCEDURE Fib(n: CARDINAL): CARDINAL;
BEGIN
  INC(calls);
  IF n < 2 THEN
    RETURN n
  END;
  RETURN Fib(n - 1) + Fib(n - 2)
END Fib;

BEGIN
  k := 5;
  WHILE k <= 30 DO
    calls := 0;
    f := Fib(k);
    WriteString("fib("); WriteCard(k, 2); WriteString(") = ");
    WriteCard(f, 6); WriteString(" after ");
    WriteCard(calls, 7); WriteString(" calls"); WriteLn;
    INC(k, 5)
  END
END fibonacci.

Fib calls itself twice, and the two calls compute the same values again and again: Fib(n - 1) computes Fib(n - 2) once more. The number of calls grows by a factor of about 1.6 with each step of n, so fib(30) already needs more than two and a half million calls.

$ gm2 -fiso fibonacci.mod -o fibonacci
$ ./fibonacci
fib( 5) =      5 after      15 calls
fib(10) =     55 after     177 calls
fib(15) =    610 after    1973 calls
fib(20) =   6765 after   21891 calls
fib(25) =  75025 after  242785 calls
fib(30) = 832040 after 2692537 calls

Memoisation

The repeated work disappears when each value is computed only once and stored. This technique is called memoisation. The table of known values is an array indexed by n.

memo.mod
MODULE memo;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

CONST
  Last = 45;

VAR
  known: ARRAY [0..Last] OF CARDINAL;
  calls, k, i: CARDINAL;

PROCEDURE Fib(n: CARDINAL): CARDINAL;
BEGIN
  INC(calls);
  IF n < 2 THEN
    RETURN n
  END;
  IF known[n] = 0 THEN
    known[n] := Fib(n - 1) + Fib(n - 2)
  END;
  RETURN known[n]
END Fib;

BEGIN
  k := 15;
  WHILE k <= Last DO
    FOR i := 0 TO Last DO
      known[i] := 0
    END;
    calls := 0;
    WriteString("fib("); WriteCard(k, 2); WriteString(") = ");
    WriteCard(Fib(k), 10); WriteString(" after ");
    WriteCard(calls, 0); WriteString(" calls"); WriteLn;
    INC(k, 15)
  END
END memo.

A zero in known means that the value has not been computed yet; every Fibonacci number from 1 up is positive. The first call of Fib(n) computes the value and stores it, and every later call returns it from the table. The number of calls is now 2n − 1. The table is cleared before each run so that the counts are comparable. fib(45) is the largest value that fits into a CARDINAL, so the table ends at 45.

$ gm2 -fiso memo.mod -o memo
$ ./memo
fib(15) =        610 after 29 calls
fib(30) =     832040 after 59 calls
fib(45) = 1134903170 after 89 calls

Towers of Hanoi

In the Towers of Hanoi puzzle, a stack of disks of different sizes has to be moved from peg A to peg C, one disk at a time, never putting a larger disk on a smaller one. Peg B can hold disks in between.

hanoi.mod
MODULE hanoi;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  moves: CARDINAL;

PROCEDURE Move(n: CARDINAL; from, to, via: CHAR);
BEGIN
  IF n > 0 THEN
    Move(n - 1, from, via, to);
    INC(moves);
    WriteString("disk "); WriteCard(n, 0);
    WriteString(": "); WriteChar(from);
    WriteString(" -> "); WriteChar(to); WriteLn;
    Move(n - 1, via, to, from)
  END
END Move;

BEGIN
  moves := 0;
  Move(3, 'A', 'C', 'B');
  WriteCard(moves, 0); WriteString(" moves"); WriteLn
END hanoi.

To move n disks, Move first moves the top n - 1 disks out of the way to the spare peg, then moves the largest disk, and finally moves the n - 1 disks on top of it. The parameters swap their roles in the two recursive calls. The base case is zero disks, where there is nothing to do. n disks take 2n − 1 moves.

$ gm2 -fiso hanoi.mod -o hanoi
$ ./hanoi
disk 1: A -> C
disk 2: A -> B
disk 1: C -> B
disk 3: A -> C
disk 1: B -> A
disk 2: B -> C
disk 1: A -> C
7 moves

Fast exponentiation

Recursion that halves the problem at each step is very fast. The power xn can be computed from xn DIV 2 with one or two multiplications.

power.mod
MODULE power;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  calls: CARDINAL;

PROCEDURE Power(x, n: CARDINAL): CARDINAL;
VAR
  half: CARDINAL;
BEGIN
  INC(calls);
  IF n = 0 THEN
    RETURN 1
  END;
  half := Power(x, n DIV 2);
  IF ODD(n) THEN
    RETURN half * half * x
  END;
  RETURN half * half
END Power;

PROCEDURE Show(x, n: CARDINAL);
VAR
  p: CARDINAL;
BEGIN
  calls := 0;
  p := Power(x, n);
  WriteCard(x, 0); WriteString("^"); WriteCard(n, 0);
  WriteString(" = "); WriteCard(p, 0);
  WriteString(" in "); WriteCard(calls, 0); WriteString(" calls"); WriteLn
END Show;

BEGIN
  Show(2, 10);
  Show(3, 20);
  Show(2, 31);
  Show(1, 1000000)
END power.

For an even n, xn is the square of xn/2; for an odd n, the square has to be multiplied by x once more. The result of the recursive call is stored in half, so it is computed only once. The number of calls grows with the number of binary digits of n: a million needs 21 calls instead of a million multiplications. The results must fit into a CARDINAL.

$ gm2 -fiso power.mod -o power
$ ./power
2^10 = 1024 in 5 calls
3^20 = 3486784401 in 6 calls
2^31 = 2147483648 in 6 calls
1^1000000 = 1 in 21 calls

Working on an array

A recursive procedure can work on part of an array, given by its first and last index. Sum takes one element off the front, and Largest splits the range in two halves.

slices.mod
MODULE slices;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;

VAR
  data: ARRAY [0..7] OF INTEGER;

PROCEDURE Sum(VAR a: ARRAY OF INTEGER; lo, hi: CARDINAL): INTEGER;
BEGIN
  IF lo > hi THEN
    RETURN 0
  END;
  RETURN a[lo] + Sum(a, lo + 1, hi)
END Sum;

PROCEDURE Largest(VAR a: ARRAY OF INTEGER; lo, hi: CARDINAL): INTEGER;
VAR
  mid: CARDINAL;
  left, right: INTEGER;
BEGIN
  IF lo = hi THEN
    RETURN a[lo]
  END;
  mid := (lo + hi) DIV 2;
  left := Largest(a, lo, mid);
  right := Largest(a, mid + 1, hi);
  IF left > right THEN
    RETURN left
  END;
  RETURN right
END Largest;

BEGIN
  data[0] := 12; data[1] := -5; data[2] := 31; data[3] := 7;
  data[4] := 0;  data[5] := 18; data[6] := -2; data[7] := 9;
  WriteString("sum:      "); WriteInt(Sum(data, 0, HIGH(data)), 0); WriteLn;
  WriteString("first 3:  "); WriteInt(Sum(data, 0, 2), 0); WriteLn;
  WriteString("largest:  "); WriteInt(Largest(data, 0, HIGH(data)), 0); WriteLn;
  WriteString("in 4..7:  "); WriteInt(Largest(data, 4, 7), 0); WriteLn
END slices.

Sum adds the first element of the range to the sum of the rest; an empty range, where lo has passed hi, sums to 0. Largest finds the largest element of each half and returns the larger of the two; a range of one element is its own largest element. Both procedures take the array as a VAR parameter although they do not change it: a value parameter would copy the whole array on every call.

$ gm2 -fiso slices.mod -o slices
$ ./slices
sum:      70
first 3:  38
largest:  31
in 4..7:  18

Reversing a string

A string is reversed by swapping its first and last characters and then reversing what lies between them.

reverse.mod
MODULE reverse;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length, Assign;

VAR
  word: ARRAY [0..31] OF CHAR;

PROCEDURE Swap(VAR s: ARRAY OF CHAR; i, j: CARDINAL);
VAR
  c: CHAR;
BEGIN
  c := s[i]; s[i] := s[j]; s[j] := c
END Swap;

PROCEDURE ReverseRange(VAR s: ARRAY OF CHAR; lo, hi: CARDINAL);
BEGIN
  IF lo < hi THEN
    Swap(s, lo, hi);
    ReverseRange(s, lo + 1, hi - 1)
  END
END ReverseRange;

PROCEDURE Reverse(VAR s: ARRAY OF CHAR);
BEGIN
  IF Length(s) > 1 THEN
    ReverseRange(s, 0, Length(s) - 1)
  END
END Reverse;

PROCEDURE Show(s: ARRAY OF CHAR);
BEGIN
  Assign(s, word);
  Reverse(word);
  WriteString('"'); WriteString(s); WriteString('" -> "');
  WriteString(word); WriteString('"'); WriteLn
END Show;

BEGIN
  Show("Modula-2");
  Show("level");
  Show("ab");
  Show("x");
  Show("")
END reverse.

ReverseRange swaps the ends of the range and calls itself on the range one character shorter on each side. It stops when the ends meet or cross. Reverse handles strings of zero and one character, for which Length(s) - 1 would be wrong or useless. Length and Assign come from the ISO Strings module.

$ gm2 -fiso reverse.mod -o reverse
$ ./reverse
"Modula-2" -> "2-aludoM"
"level" -> "level"
"ab" -> "ba"
"x" -> "x"
"" -> ""

Permutations

A permutation is an arrangement of all elements in some order. Recursion generates all of them: each element in turn is placed first, and the rest are permuted.

permutations.mod
MODULE permutations;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Strings IMPORT Length;

VAR
  letters: ARRAY [0..7] OF CHAR;
  count: CARDINAL;

PROCEDURE Swap(VAR s: ARRAY OF CHAR; i, j: CARDINAL);
VAR
  c: CHAR;
BEGIN
  c := s[i]; s[i] := s[j]; s[j] := c
END Swap;

PROCEDURE Permute(VAR s: ARRAY OF CHAR; k: CARDINAL);
VAR
  i: CARDINAL;
BEGIN
  IF k + 1 >= Length(s) THEN
    INC(count);
    WriteString(s);
    IF count MOD 6 = 0 THEN WriteLn ELSE WriteString(" ") END
  ELSE
    FOR i := k TO Length(s) - 1 DO
      Swap(s, k, i);
      Permute(s, k + 1);
      Swap(s, k, i)
    END
  END
END Permute;

BEGIN
  count := 0;
  letters := "abcd";
  Permute(letters, 0);
  WriteCard(count, 0); WriteString(" permutations of "); WriteString(letters);
  WriteLn
END permutations.

Permute(s, k) leaves the first k characters in place and permutes the rest. It swaps each of the remaining characters into position k, permutes the positions after it and swaps the character back, so the string is unchanged when the loop moves on. This pattern, trying a choice and undoing it, is called backtracking. Four letters give 4! = 24 permutations.

$ gm2 -fiso permutations.mod -o permutations
$ ./permutations
abcd abdc acbd acdb adcb adbc
bacd badc bcad bcda bdca bdac
cbad cbda cabd cadb cdab cdba
dbca dbac dcba dcab dacb dabc
24 permutations of abcd

Overflow

Recursive procedures often produce large numbers, and a CARDINAL holds at most 4294967295.

limits.mod
MODULE limits;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

VAR
  k: CARDINAL;

PROCEDURE Fact(n: CARDINAL): CARDINAL;
BEGIN
  IF n = 0 THEN
    RETURN 1
  END;
  RETURN n * Fact(n - 1)
END Fact;

BEGIN
  FOR k := 11 TO 14 DO
    WriteCard(k, 2); WriteString("! = ");
    WriteCard(Fact(k), 0); WriteLn
  END
END limits.

13! is 6227020800, which does not fit. By default gm2 does not check whole-number arithmetic, and the results from 13! on are wrong without any warning. With -fsoft-check-all the program stops at the first multiplication that overflows, prints the place in the source and exits with status 134.

$ gm2 -fiso limits.mod -o limits
$ ./limits
11! = 39916800
12! = 479001600
13! = 1932053504
14! = 1278945280
$ gm2 -fiso -fsoft-check-all limits.mod -o limits
$ ./limits
11! = 39916800
12! = 479001600
13! = limits.mod:13:12: In procedure ‘Fact’
limits.mod:13:12:whole value multiplication will cause a range overflow
$ echo $?
134

Stack depth

Each active call occupies memory on the stack. The stack is limited, so the depth of recursion is limited as well.

depth.mod
MODULE depth;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;

PROCEDURE Count(n: CARDINAL): CARDINAL;
BEGIN
  IF n = 0 THEN
    RETURN 0
  END;
  RETURN 1 + Count(n - 1)
END Count;

BEGIN
  WriteString("depth "); WriteCard(Count(100000), 0); WriteLn;
  WriteString("depth "); WriteCard(Count(10000000), 0); WriteLn
END depth.

Count(n) calls itself n times before it returns. A hundred thousand nested calls work, but ten million exhaust the stack, which is 8 MB by default on Linux. The program is killed by a segmentation fault, signal 11, and the shell reports the status 128 + 11 = 139. The second line is cut short, and there is no error message. A loop needs no stack, so a recursion that only counts down should be a loop; recursion pays off where the problem splits into smaller parts, as in Largest and in the sorting algorithms.

$ gm2 -fiso depth.mod -o depth
$ ./depth
depth 100000
depth 
$ echo $?
139

Source

The GNU Modula-2 manual

Recursion in computer science

In this article we have written recursive procedures in Modula-2, traced their calls, removed repeated work with memoisation, solved the Towers of Hanoi, computed powers by halving, worked on arrays and strings, generated permutations, and met the limits of overflow and stack depth. The sorting and searching articles use recursion in quicksort, merge sort and binary search, and the calculator parses nested expressions with mutually recursive procedures.

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 Modula-2 tutorials.