Recursion in C++
Recursion is a process in which a function calls itself directly or indirectly. The function which calls itself is known as recursive function. It uses the approach of divide and conquer. Its usage helps in solving a complex iterative problem by dividing it into sub parts.
Recursion leads to multiple iterative calls. Hence, it is essential to have a base case in order to terminate the recursion.
Syntax:
int fun()
{
fun(); //fun() calling fun() function
}
Let's see a simple example of recursion.
recursionfunction(){
recursionfunction(); //calling self function
Let's see an example to print factorial number using recursion in C++ language.
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating the condition*/
else
{
return(n*factorial(n-1));
}
}
Output:
Enter any number: 4
Factorial of a number is: 24
Advantages
- It uses less numbers of codes.
- It is used in solving problems concerning data structures and advanced algorithms such as tree traversal and graphs.
Disadvantages
- Lots of stack space usage takes place.
- It takes more processing time.
- It can be more difficult to debug.
0 Comments