English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Recursive function
In this article, you will learn to create recursive functions. Functions that call themselves.that calls itselffunction
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).
// 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
Suppose the user inputs4and passing it to this factorial() function.
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.
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.
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.
In the fourth factorial() function, test the if statement for false expression inside. return 1; statement is executed, returns1Up to the third factorial() function.
The third factorial() function will2Returns to the second factorial() function.
The second factorial() function will6Returns to the first factorial() function.
Finally, the first factorial() function will24Returns to the main() function, which will display on the screen.