Recursion is when a function calls itself. It's handy whenever you can break a problem down into smaller versions of the same problem — think factorials, tree traversal, or walking through directories.
c
#include <stdio.h>
int sum(int n) {
if (n == 0) {
return 0;
}
return n + sum(n - 1);
}
int main() {
printf("%d", sum(5));
return 0;
}sum(5) becomes 5 + sum(4), and it keeps calling itself from there. n == 0 is when it hits the base case and the recursion stops.
You should see
15Info
Without a base case, recursion never stops calling itself — and that can blow the stack (stack overflow).