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);
EndAlgorithmOutput
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
Factorial(4)is called, and it needsFactorial(3).2Frames pile up until
Factorial(1), the base case.3The base case returns 1 and its frame disappears.
4Every frame multiplies and returns: 2, 6 and finally 24.
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);
EndAlgorithmOutput
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.