Classic Recursive Problems
Factorial and Fibonacci.
Classic Problems
Some problems map naturally onto recursion. Learning the classics gives you patterns you can reuse.
In this lesson we cover factorial, Fibonacci, sum of digits, greatest common divisor, and reversing output.
Factorial
The factorial of n is n times the factorial of n minus 1, with 1! equal to 1.
This is the textbook recursion: a clear base case and one recursive call.
#include <stdio.h>
long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main(void) {
printf("%ld\n", factorial(6));
return 0;
}All lessons in this course
- How Recursion Works
- Classic Recursive Problems
- Recursion vs Iteration
- Avoiding Stack Overflow