Skip to content

Instantly share code, notes, and snippets.

@ShahStavan
Created July 3, 2021 09:57
Show Gist options
  • Save ShahStavan/8f730ef8f3ed3538814369328df91a7f to your computer and use it in GitHub Desktop.
Save ShahStavan/8f730ef8f3ed3538814369328df91a7f to your computer and use it in GitHub Desktop.
Let's understand Recursion in Best Possible way in C++ 🙌. We will take example of Factorial✌️
In First case what happens main function gets the input from user and pass it as Parameter to function called factorial
Let's assume n = 4
int factorial(int n)
{
cout<<n<<endl; // Here we display n
if(n==0){ // if n becomes 0 we return 1
return 1;
}
int smalloutput = factorial(n-1); //This is recursion part where we call function again
return n*smalloutput; // At last we get our result
}
First we display n that is 4
Now we check whether n is 0 or not. Well still n is not zero so condition is not satisfied
smalloutput variable calls function itself.
So, what happens here is functtion is calling itself and n=4 so it will become 3,2,1 and 0 when it becomes 0 it will return 1.
And we are returning n*smalloutput that is
0*1 = 1*1 = 1 [Because we return 1 when n becomes 0]
1*1 = 1 [As we know after 0 we have 1 waiting in queue so we will consider 1 as smalloutput and 1 as n]
1*2 = 2 [smalloutput = 1 and n = 2]
2*3 = 6 [smalloutput = 2 and n = 3]
6*4 = 24 [smalloutput = 24 and n = 4]
Output = 24
So, this is how Recursion works.
Hope you have learnt How Recursion works🤘
See you in next topic👋
//Let's understand how this Works
#include<iostream>
using namespace std;
int factorial(int n)
{
cout<<n<<endl; // Here we display n
if(n==0){ // if n becomes 0 we return 1
return 1;
}
int smalloutput = factorial(n-1); //This is recursion part where we call function again
return n*smalloutput; // At last we get our result
}
int main()
{
int n;
cout<<"Enter Number: "<<endl;
cin>>n;
int result = factorial(n); //Here it calls the function named factorial and we pass parameter n
cout<<"Result = "<<result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment