Recursive functions are executed in a
2009
Recursive functions are executed in a
- A.
First in first out-order
- B.
Last in first out-order
- C.
Parallel fashion
- D.
Load balancing
Show answer & explanation
Correct answer: B
CONCEPT: In a recursive execution, every call to a function creates a new activation record (stack frame) that is pushed onto the program's call stack; that frame is popped only when that specific call returns. Because every push and pop acts on the top of the stack, the most recently made call is always the first one to finish and return -- this is the Last-In-First-Out (LIFO) discipline.
APPLICATION (trace factorial(3)):
factorial(3)is invoked. It cannot finish yet, so its frame is pushed onto the stack, and it callsfactorial(2).factorial(2)is invoked next. Its frame is pushed abovefactorial(3)'s frame, and it callsfactorial(1).factorial(1)is invoked next. Its frame is pushed abovefactorial(2)'s frame, and it callsfactorial(0).factorial(0)is the base case -- it returns immediately, so its frame, the LAST one pushed, is the FIRST one popped.factorial(1)resumes using that returned value, computes its own result, then returns -- its frame is popped second.factorial(2)resumes next, computes its result, then returns -- its frame is popped third.factorial(3)resumes last, computes the final result, then returns -- its frame, the FIRST one pushed, is the LAST one popped.
CROSS-CHECK: If execution instead followed a First-In-First-Out order, the outermost call (the first one made) would have to complete before any inner call even started -- which contradicts the fact that a call must wait for its own nested call to return before it can proceed. Recursive execution also runs as a single sequential chain of calls and returns on one call stack, not as multiple call streams progressing at once, and it involves no distribution of work across separate processing units. The push/pop trace above confirms the last call made is the first call completed: Last-In-First-Out order.