All lessonsOpen Open Open Open Open
5. Recursion
Recursion fundamentals
0 of 5 activities0%
Reading 1
Base case + smaller problem
Every recursive function needs a base case that stops the chain, and a recursive case that moves toward it.
The call stack stores frames. Too deep → stack overflow.
Classic: factorial, Fibonacci (naive is slow), tree DFS.
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}Check 2
Missing base
Without a base case, recursion typically
Fill in 3
Stop
Try it 4
Fact 5
Recursive factorial.
main.cpp
Loading editor…
Output will appear here.
Assignment 5
Sum 1..n recursive
Write int sumTo(int n) that returns 1+...+n recursively. Read n and print sumTo(n).
main.cpp
Loading editor…