C++ Recursion
In this tutorial, we will learn about recursive function in C++ and its working with the help of examples.
A function that calls itself is known as a recursive function. And, this technique is known as recursion.
Factorial of a Number Using Recursion
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
cout << "Enter a non-negative number: ";
cin >> n;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output
Enter a non-negative number: 4
Factorial of 4 = 24