Recursion (recursive) function is such function which call itself again and again. A recursion function call takes within the same function. The condition where the recursive function terminates is called the base case.
Syntax:
C++ Recursion Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> using namespace std; int factorial(int); int main() { int n,fact; cout<<"Enter a number to find factorial: "; cin >> n; fact=factorial(n); cout << "Factorial of " << n <<" = " << fact; return 0; } int factorial(int n) { if (n > 1) { return n*factorial(n-1); } else { return 1; } } |
Output:
1 2 3 4 |
Enter a number to find factorial: 5 Factorial of 5= 120 |