Resources | Subject Notes | Computer Science | Lesson Plan
Recursion is a powerful programming technique where a function calls itself within its own definition. It's a way to solve problems by breaking them down into smaller, self-similar subproblems. A recursive function has a base case and a recursive case.
When a recursive function is called, it's placed on the call stack. Each recursive call creates a new frame on the stack, storing the function's parameters and local variables. When the base case is reached, the function returns a value, and the stack frames are unwound, with each frame returning its value to the caller.
A classic example of recursion is calculating the factorial of a non-negative integer. The factorial of n (denoted as n!) is the product of all positive integers less than or equal to n. For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.
The factorial function can be defined recursively as follows:
factorial(n) = { 1, if n = 0 (base case) n * factorial(n-1), if n > 0 (recursive case) }
Call | n | Return Value |
---|---|---|
factorial(5) | 5 | 5 * factorial(4) |
factorial(4) | 4 | 4 * factorial(3) |
factorial(3) | 3 | 3 * factorial(2) |
factorial(2) | 2 | 2 * factorial(1) |
factorial(1) | 1 | 1 * factorial(0) |
factorial(0) | 0 | 1 (base case) |
Tail recursion is a special form of recursion where the recursive call is the very last operation performed in the function. Some compilers can optimize tail-recursive functions into iterative code, eliminating the stack overhead. However, not all compilers support tail-call optimization.
While not directly implementable in standard C++, this illustrates the concept.
factorial_tail_recursive(n) = { if (n == 0) return 1; else return n * factorial_tail_recursive(n - 1); // Recursive call is the last operation }