13 C++ Recursion (With Example)
13 C++ Recursion (With Example)
In this tutorial, we will learn about recursive function in C++ and its working with
the help of examples.
A DV E RT I S E M E N T S
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;
}
}
Output
A DV E RT I S E M E N T S
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.
A DV E RT I S E M E N T S
Related Tutorials
Tutorials Examples
Join our newsle er for the latest Python 3 Tutorial Python Examples
updates.
JavaScript Tutorial JavaScript Examples
Swi Tutorial
C# Tutorial
DSA Tutorial
Company Apps
Privacy Policy
Contact
Blog
Youtube