Chris Dedman-Rollet
~ Per Astra Ad Astra ~

C++ Recursion


By
on

What is recursion?

Recursion is a programming technique in which a function calls itself, typically with a different input each time. This allows the function to repeat a set of operations on a smaller or simpler version of the same problem, eventually arriving at a solution to the original problem.

What is it used for?

Recursion is often used to solve problems that can be naturally divided into smaller, similar subproblems. For example, a recursive function might take as input a list of numbers and a target sum, and return true if any combination of numbers in the list adds up to the target sum. To solve this problem, the function could first check if any of the numbers in the list equals the target sum, and return true if it does. If not, it could call itself with a smaller list containing all of the numbers except the first one, and return true if the function called on the smaller list returns true.

How is it implemented?

Here's a simple example of a recursive function in C++ that computes the factorial of a number:


// Recursive function to compute the factorial of a number
int factorial(int n)
{
    // Base case: if n is 0, the factorial is 1
    if (n == 0)
        return 1;

    // Recursive case: otherwise, the factorial is n multiplied by the
    // factorial of n - 1
    else
        return n * factorial(n - 1);
}
                    

In this example, the factorial function calls itself with a smaller value of n each time, until it reaches the base case where n is 0. At this point, the function returns the result of the computation (1 in this case), and the previous recursive calls can use this result to compute the factorial of their respective inputs.

One thing to be careful of when using recursion is to make sure that the function has a well-defined base case that will eventually be reached, and that the recursive calls eventually reduce the size of the problem being solved. If these conditions are not met, the function will keep calling itself indefinitely, leading to an infinite recursion.

Overall, recursion is a powerful and elegant programming technique that can be used to solve a wide range of problems in C++ and other programming languages. I hope this brief overview has helped to make the concept of recursion more understandable to you!