C++ Recursion
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.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
The figure below shows how recursion works by calling itself over and over again.
To prevent infinite recursion, if...else statement (or similar approach) can be used
where one branch makes the recursive call and the other doesn't.
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
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;
}
}
Run Code
Output
As we can see, the factorial() function is calling itself. However, during each
call, we have decreased the value of n by 1 . When n is less than 1 , the
factorial() function ultimately returns the output.