retagged by
1,424 views
4 votes
4 votes

Consider following recursive functions:

function fib(n : integer); integer
begin
if (n = 0) or (n = 1) then fib = 1
else
fib = fib(n-l) + fib(n-2)
end

The above function is run on a computer with a stack of $x$ bytes. Assume that only return address & parameter are passed on the stack and an integer value & return value take $2$ $bytes$ each. If we can execute this function for maximum value $n = 10$ without overflowing the stack. Then the size of the stack is ______ $Bytes$.

retagged by

2 Answers

Best answer
10 votes
10 votes

" All computer really needs to remember for each active function call is values of arguments & local variables and the location of the next statement to be executed when control goes back" .

read this  slide number 3 and 4 -->http://www-inst.eecs.berkeley.edu/~cs164/fa12/ta-materials/recursionOnStack.ppt  .

Here we have n = 10, running successfully, meaning function calls from $n = 1,2,\dots ,10$ can be live at a time on stack (maximum recursion depth and not total no. of recursive calls). So, this should mean a minimum stack space of $10 \times 4 = 40$ bytes.

edited by
0 votes
0 votes
Answer should be 36 Bytes, because f(1) and f(0) won't be pushed on stack,
when the function call is f(2), and f(2) calls f(1) then F(2) will be pushed to stack but why should we push f(1) when there is no call after f(1).
@Bikram @Arjun please clear the doubt
Answer:

Related questions