Recursion
Recursion is a technique in which a function calls itself to solve a problem by breaking it into smaller instances of the same problem. Every recursive function needs a base case that stops the calls, otherwise it recurses forever and causes a stack overflow.
Recursion suits problems that are naturally self-similar, such as factorials, tree and graph traversal, divide-and-conquer sorting (merge sort, quick sort) and backtracking. Each call uses stack memory, so very deep recursion is sometimes rewritten as a loop.
static long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
factorial(5); // 120