Topic 1
Recursion
What is Recursion?
A function that calls itself to solve smaller sub-problems. Every recursive function needs:
- Base Case โ stops the recursion
- Recursive Case โ function calls itself with simpler input
Each call is pushed onto the call stack. When base case is hit, calls return one by one (unwinding).
โก
LIFO in call stack โ Last called function returns first. Print AFTER recursive call = ascending.
๐ฏ
Base case is mandatory โ Without it โ infinite recursion โ stack overflow.
๐ฌ
Print before call = descending. Print after call = ascending.
๐
Time: O(n) for linear recursion. Space: O(n) due to call stack.
Exam Tip โ Tracing Output
For f(5) where print is before AND after call: 5 3 1 1 3 5
Going IN: prints 5, 3, 1 โ Coming BACK: prints 1, 3, 5
Pattern: n % 10 = last digit, n / 10 = remove last digit