Recursion Examples in CS Thinking
Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Recursion.
This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.
Concept 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.
Read the full concept explanation βHow to Use These Examples
- Read the first worked example with the solution open so the structure is clear.
- Try the practice problems before revealing each solution.
- Use the related concepts and background knowledge badges if you feel stuck.
What to Focus On
Core idea: Every recursion needs a base case (when to stop) and a recursive case (how to continue).
Common stuck point: Without a base case, recursion never endsβthe program crashes with a stack overflow error.
Worked Examples
Example 1
hardSolution
- 1 Step 1: factorial(4) = 4 * factorial(3).
- 2 Step 2: factorial(3) = 3 * factorial(2). factorial(2) = 2 * factorial(1). factorial(1) = 1 (base case).
- 3 Step 3: Unwind: 2*1=2, 3*2=6, 4*6=24.
Answer
Example 2
hardPractice Problems
Try these problems on your own first, then open the solution to compare your method.
Example 1
hardExample 2
hardBackground Knowledge
These ideas may be useful before you work through the harder examples.