C++ Recursive Functions

ww‮‬w.theitroad.com

A recursive function in C++ is a function that calls itself. Recursive functions are useful when solving problems that can be broken down into smaller subproblems, and the solution to the original problem can be obtained by combining the solutions to the subproblems.

To implement a recursive function, you need to define a base case that stops the recursion and one or more recursive cases that call the function with a smaller input. For example, here is a simple recursive function that calculates the factorial of a positive integer:

int factorial(int n) {
    if (n == 0) {
        return 1; // base case: factorial(0) = 1
    } else {
        return n * factorial(n - 1); // recursive case
    }
}

In this example, the base case is when n is equal to 0, and the function returns 1. The recursive case is when n is greater than 0, and the function calls itself with the argument n - 1 and multiplies the result by n. This continues until the base case is reached, and the function returns the final result.

It is important to note that recursive functions can use a lot of memory and CPU time, especially when the recursion depth is large. To avoid this, it is often possible to convert a recursive function into an iterative one that uses loops instead of recursion.