Recursive Subprograms
Recursive Subprograms
1. Base case: This is the condition under which the function stops calling itself.
It prevents infinite recursion and allows the function to return a result.
2. Recursive case: This is where the function calls itself with a modified
argument that progresses toward the base case.
def factorial(n):
if n == 0: # base case
return 1
else: # recursive case
return n * factorial(n - 1)
In this example, the function calls itself with the argument n - 1 until it reaches
the base case where n == 0.
Key Points:
● Memory usage:
Every recursive call adds a new frame to the call stack, which
can be problematic if recursion is too deep (leading to stack overflow).
● Efficiency: Recursive functions are often less efficient in terms of time and
space compared to iterative approaches, especially if the recursion depth is
large.
Stack-Based Subprograms
● Return address: The location where the program should continue execution
after the function finishes.
● Parameters: The arguments passed to the function.
● Local variables: Variables declared within the function.
● Saved registers: The values of registers that the function may modify, which
need to be restored after the function finishes.
Once the function finishes execution, the activation record is popped from the
stack, and control returns to the calling function. This stack-based approach is
essential for managing function calls in most programming languages, especially in
the context of recursion.
Each recursive call creates a new stack frame, and the stack unwinds as the
functions return.
1. Call factorial(3) -> Push activation record for factorial(3) onto the stack.
2. Call factorial(2) -> Push activation record for factorial(2) onto the stack.
3. Call factorial(1) -> Push activation record for factorial(1) onto the stack.
4. Call factorial(0) -> Push activation record for factorial(0) onto the stack.
- factorial(0) returns 1.
5. Pop activation record for factorial(0).
6. factorial(1) returns 1 * 1 = 1.
7. Pop activation record for factorial(1).
8. factorial(2) returns 2 * 1 = 2.
9. Pop activation record for factorial(2).
10. factorial(3) returns 3 * 2 = 6.
11. Pop activation record for factorial(3).
In this example, each recursive call generates a new activation record on the stack.
As each function completes, its corresponding stack frame is popped off the stack.
In Summary: