Recursion is a process in which a function calls itself directly or indirectly to solve a problem. In this article, we will learn Recursion in C++ and its implementation.
Syntax:
int fun() { .... fun() }
C++ Program to find the Factorial of a number.
#include<iostream> using namespace std; //function to find factorial int factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); } int main() { int num; cout<<"Enter a number: "; cin>>num; cout<<"Factorial of given number: "<<factorial(num); return 0; }
Enter a number: 5
Factorial of given number: 120
Working of Recursion.
Types of Recursion.
- Direct Recursion
- Indirect Recursion
- Tail Recursion
- Non-Tail Recursion
1. Direct Recursion.
//Example of direct Recursion void fun() { //some code fun(); }
2. Indirect Recursion.
//Example of indirect Recursion void fun_1() { //some code fun_2(); } void fun_2() { //some code fun_1(); }
3. Tail Recursion.
//Example of Tail Recursion in C++ #include<iostream> using namespace std; //recursive function int fun(int n) { if(n == 0) return 0; else cout<<n<<" "; return fun(n - 1); } int main(){ //function call fun(3); return 0; }
3 2 1
4. Non-Tail Recursion.
//Non-Tail Recursion Example in C++ #include<iostream> using namespace std; void fun(int n) { if(n == 0) return; fun(n - 1); cout<<n<<" "; } int main() { //function call fun(3); return 0; }
1 2 3
Conclusion.
- Every recursion program can be written as iterative.
- Every recursion program can be modeled into an iterative program but recursive programs are more elegant and require relatively fewer lines of code.
- The recursive program requires more space in memory than iterative programs.













