Step 6 of 7
Recursion
A function can call itself. That's recursion. Every recursive function needs a base case that stops, and a step that moves toward it.
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // smaller problem
}
Your turn: write int fib(int n) returning the n-th Fibonacci number, where fib(0) = 0, fib(1) = 1 and every later number is the sum of the two before it.
Previous: Scope and pass by value Next: Challenge: is it prime?