Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Auxiliary Space with Recursive Functions in C Program?
Here we will see how auxiliary space is required for recursive function calls and how it differs from normal function calls in terms of memory usage.
Syntax
returnType functionName(parameters) {
// Base case
if (condition)
return baseValue;
// Recursive case
return functionName(modifiedParameters);
}
Recursive Function Example
Consider a recursive factorial function −
#include <stdio.h>
long fact(int n) {
if (n == 0 || n == 1)
return 1;
return n * fact(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %ld<br>", num, fact(num));
return 0;
}
Factorial of 5 is 120
How Recursive Calls Use Stack Space
When fact(5) is called, the function calls are stored in the stack as follows −
Space Complexity Analysis
The space complexity differs between recursive and iterative approaches −
| Function Type | Space Complexity | Reason |
|---|---|---|
| Recursive Function | O(n) | Each recursive call creates a new stack frame |
| Iterative Function | O(1) | Uses same stack frame repeatedly |
Iterative vs Recursive Comparison
Here's an iterative version of the factorial function for comparison −
#include <stdio.h>
long factIterative(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
long factRecursive(int n) {
if (n == 0 || n == 1)
return 1;
return n * factRecursive(n - 1);
}
int main() {
int num = 5;
printf("Iterative factorial of %d: %ld<br>", num, factIterative(num));
printf("Recursive factorial of %d: %ld<br>", num, factRecursive(num));
return 0;
}
Iterative factorial of 5: 120 Recursive factorial of 5: 120
Key Points
- Recursive functions have O(n) auxiliary space due to multiple stack frames
- Iterative functions have O(1) auxiliary space as they reuse the same stack frame
- Each recursive call stores local variables, parameters, and return addresses on the stack
- Deep recursion can lead to stack overflow for large input values
Conclusion
Recursive functions require O(n) auxiliary space because each call creates a new stack frame that remains until the recursion unwinds. In contrast, iterative functions maintain constant O(1) space complexity by reusing the same memory frame throughout execution.
Advertisements
