Skip to content

SpecificationVII · Subroutines

7.7

Recursion

A recursive subprogram calls itself with a smaller problem, until it reaches a case so simple that it is solved without calling itself.

Markdown version

7.7.1 How it works

Every recursion has two parts:

  • the base case, which answers without calling itself;
  • the recursive case, which calls itself with a smaller problem and uses its answer.

ProgramThe factorial

Subroutine Factorial(n As Integer) As Integer
  If n <= 1 Then
    Return 1;
  EndIf
  Return n * Factorial(n - 1);
EndSubroutine

Algorithm Principal
  Write Factorial(5);
EndAlgorithm

Output

120

The program finishes normally.

Every call has its own frame, with its own n. Calls pile up until the base case and are then resolved from the top down.

  1. 1Factorial(4) is called, and it needs Factorial(3).

  2. 2Frames pile up until Factorial(1), the base case.

  3. 3The base case returns 1 and its frame disappears.

  4. 4Every frame multiplies and returns: 2, 6 and finally 24.

Figure 7.7-1.Factorial(4) stacks four frames, each with its own n. The top one resolves first and hands its value to the one below.

Four frames stacked from Factorial(4) to Factorial(1). The base case returns 1 and every frame multiplies: 2, 6 and 24.

Nothing needs to be declared in advance, and two subprograms can call each other:

ProgramMutual recursion

Subroutine EsPar(n As Integer) As Boolean
  If n = 0 Then
    Return True;
  EndIf
  Return EsImpar(n - 1);
EndSubroutine

Subroutine EsImpar(n As Integer) As Boolean
  If n = 0 Then
    Return False;
  EndIf
  Return EsPar(n - 1);
EndSubroutine

Algorithm Principal
  Write EsPar(10), " ", EsImpar(7);
EndAlgorithm

Output

true true

The program finishes normally.

In short

  • A recursive subprogram calls itself with a smaller problem.
  • It needs a base case that answers without calling itself.
  • Every call has its own frame.
  • Without a base case, the engine stops it when depth runs out.