Worked example 1
Write a recursive function in pseudocode, Factorial(n), that calculates the factorial of a non-negative integer . Trace the execution for Factorial(4).
Show solution outline
FUNCTION Factorial(n : INTEGER) RETURNS INTEGER
IF n = 0 THEN
RETURN 1 // Base Case
ELSE
RETURN n * Factorial(n - 1) // Recursive Step
ENDIF
ENDFUNCTION
Execution Trace for Factorial(4):
- Factorial(4) is called. Since 4 ≠ 0, it computes 4 * Factorial(3).
- Factorial(3) is called. Since 3 ≠ 0, it computes 3 * Factorial(2).
- Factorial(2) is called. Since 2 ≠ 0, it computes 2 * Factorial(1).
- Factorial(1) is called. Since 1 ≠ 0, it computes 1 * Factorial(0).
- Factorial(0) is called. , so it hits the base case and returns 1.
The call stack now unwinds: 6. The call to Factorial(1) receives 1 and returns . 7. The call to Factorial(2) receives 1 and returns . 8. The call to Factorial(3) receives 2 and returns . 9. The original call to Factorial(4) receives 6 and returns .
Final Answer: 24