Recursion
Recursion
We can also write the solution as a recursive algorithm. Consider what happens after the first value
has been output. The remaining numbers follow the same pattern of counting down from the next
smaller value. The base case is when n reaches 0. 0 will be output but no further numbers. The
general case is outputting n and then counting down from (n-1).
Task
Coding a recursive procedure
statements after CALL countUpTo(n-1) are not executed until control returns to this statement as the
recursive calls unwind. What is the effect of moving the OUTPUT statement to the end of the
procedure?
Tracing a recursive function
A recursive function has a statement after the recursive ca ll to itself: the RETURN statement.
Again we show what happens when the recursive ca lls unwind by fi lling in more rows in the
trace table. Let's consider the factorial function again .
FUNCTION Factorial(n : INTEGER) RETURNS INTEGER
IF n = 0 THEN
Result 1
ELSE
Result .... n * Factorial (n-1)
ENDIF
RETURN Result
END FUNCTION
Tracing a recursive function
Benefits and drawbacks of recursion