English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ <cmath>

Recursive function

In this article, you will learn to create recursive functions. Functions that call themselves.that calls itselffunction

Recursion in C is called a recursive function. And this technique is called recursion. ++How does it work?

void recurse()
{
    ... .. ...
    recurse();
    ... .. ...
}
int main()
{
    ... .. ...
    recurse();
    ... .. ...
}

The following diagram shows how recursion calls are made.

Recursion continues until a certain condition is met.

To prevent infinite recursion, you can use the if ... else statement where one branch makes a recursive call and the other does not.if ... else statement(or similar method).

Example1: Using recursion to decompose a number

// n's factorial = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() 
{
    int n;
    cout << "Enter a number to find the factorial: ";
    cin >> n;
    cout << "number " << n << "\n's factorial= " << factorial(n);
    return 0;
}
int factorial(int n) 
{
    if (n > 1) 
    {
        return n*factorial(n-1;
    }
    else 
    {
        return 1;
    }
}

Output Result

Enter a number to find the factorial: 4
number 4the factorial of 24

Usage Explanation: How does this instance work?

Suppose the user inputs4and passing it to this factorial() function.

  1. In the first factorial() function, testingif statementfor true. return num*factorial(num-1; The statement is executed, calling the second factorial() function, passing the parameter num-1as3.

  2. In the second factorial() function, testing the expression inside the if statement for true. return num*factorial(num-1; The statement is executed, calling the third factorial() function, passing the parameter num-1as2.

  3. In the third factorial() function, testing the expression inside the if statement for true. return num*factorial(num-1; The statement is executed, calling the fourth factorial() function and passing the parameter num-1is1.

  4. In the fourth factorial() function, test the if statement for false expression inside. return 1; statement is executed, returns1Up to the third factorial() function.

  5. The third factorial() function will2Returns to the second factorial() function.

  6. The second factorial() function will6Returns to the first factorial() function.

  7. Finally, the first factorial() function will24Returns to the main() function, which will display on the screen.