Practice Recursion in CS Thinking

Use these practice problems to test your method after reviewing the concept explanation and worked examples.

Quick Recap

A technique where a function calls itself to solve progressively smaller instances of the same problem.

Russian dollsβ€”open one, find a smaller one inside. Repeat until you reach the smallest.

Example 1

hard
Trace the recursive function: FUNCTION factorial(n): IF n <= 1 THEN RETURN 1. ELSE RETURN n * factorial(n-1). Call factorial(4).

Example 2

hard
What happens if a recursive function has no base case? For example: FUNCTION forever(n): RETURN forever(n+1).

Example 3

hard
Write a recursive function `sum(n)` that returns the sum 1 + 2 + ... + n. Trace sum(5).

Example 4

hard
Trace `countdown(3)` for `FUNCTION countdown(n): OUTPUT n. IF n > 0 THEN countdown(n-1)`. What is printed, and what is the base case?