Recursion

Recursion

Recursion

Recursion is a powerful programming technique in which a function calls itself in order to solve a problem. A function that uses recursion is called a recursive function. Recursion can be used to solve problems that involve repeating a task in a self-similar way.

Here’s an example of a recursive function that calculates the factorial of a non-negative integer:

				
					#include<iostream>

int factorial(int n) {

    if (n == 0) {

        return 1;

    } 

else {

        return n * factorial(n - 1);

    }

}

int main() {

    int n = 5;

    std::cout << "The factorial of" << n << " is " << factorial(n) <<std::endl;

    return 0;

}
​
				
			

In this example, the factorial function calculates the factorial of a non-negative integer n using recursion. If n is equal to 0, the function returns 1. Otherwise, the function multiplies n by the result of calling factorial with n – 1 as the argument. This process continues until n is equal to 0, at which point the function returns 1.

In the main function, we call the factorial function with the value 5, which calculates the factorial of 5 using recursion.

Recursion can be a powerful tool for solving problems, but it can also be computationally expensive and may lead to stack overflow errors if not used properly. It’s important to consider the efficiency of your recursive functions and to make sure that they have a base case that eventually terminates the recursion.

Join To Get Our Newsletter
Spread the love