// Recursive Implementation:
int factorialResult(int n) {
if (n == 0) {
return 1;
}
else {
return factorialResult(n - 1) * n;
}
}
// Iterative Implementation:
int factorialResult(int n) {
int factorialSum = 1;
for (int i = 1; i <= n; i++) {
factorialSum *= i;
}
return factorialSum;
}
In most cases in C, do recursive function implementations use more memory? And if so, is it around double the memory of a corresponding iterative function implementation?
Not "twice as much" memory, but on the order of
ntimes as much memory is likely used.All of this memory is stack memory. Stack memory is cheap to allocate compared to heap memory. A stack allocation takes O(1) time - it just moves the stack pointer.
But it's limited. Threads usually have a megabyte of stack on high-end computers to about 100KB on low-end devices. Depends on compiler settings and OS architecture. So if you invoked the recursive
factorial(500000), it would hit a literal "stack overflow" error long before the overflowed result could be returned to the caller.