c++ Recursion
C++ Recursion
In this article, you will learn about the recursion in the c++ language with an explanation of the concept of the recursion.
When the function calls itself within the body of the function is called the recursion in c++ language.
let's see an example
function(){
function();//calling itself in its body
}
For Example:
Find the factorial of the number with the help of Recursion.
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,number;
cout<<"Enter the number for finding factorial: ";
cin>>number;
fact=factorial(number); //call the recursive function
cout<<"Factorial of the number is = "<<fact<<endl; //display the factorial
return 0;
}
int factorial(int n)
{
//This is the base condition
//It is very important in recursion
//otherwise StackOverflow error happened
if(n>0)
return(n*factorial(n-1)); // if number greater than zero
else
return(1); // if number is zero then one return
}
Output:
Enter the number for finding factorial:5
Factorial of the number is 120
How recursion work?
In the above code, the function calls itself and solve the problem. In every call of function decrease by one in the value of the number until the number becomes zero. when the number is zero then return work and backtracking process start.
What is base condition?
Base condition:
In the process of recursion, first of all, find the base case of the problem. The base case is the condition when calling the function process should be stopped. The base reached and backtracking process start and find the solution to the required problem.
In the above program, the base condition is number is equal to zero.
if(n>0)
return(n*factorial(n-1));
else
return(1);
In the else part is the base case because if the value of the number is equal to zero the return one.
What is the difference between recursion and iteration process?
comparison between recursion and iteration process.
Advantages of Recursion:
The recursion used in the data structure and algorithm for example tree
It makes the code clean and short.
It makes the problem easy to solve which is needed to backtrack.
For example, undo and redo.
Disadvantages of Recursion:
It builds the stack up that's why take a lot of stack space
Increase the time of execution.
What is the indirect recursion in c++?
Indirect C++ recursion:
In this recursion, function calls another function and built the stack that's called indirect recursion.
For more clarify, let suppose an example function name one, function two, and function three. one call two functions and two calls three. In this way, indirect recursion happened.
Please write the comment,if you find anything incorrect and any problem in the above topic or you want to share more information about the above topic.
Comments
Post a Comment