Finding Factorial in C++ || Recursion

 Finding Factorial in C++ || Recursion

The logic and code are pretty simple for this. Considering that we don't have to do any exception handling.

We get the input n.
We return 1 if the input is 0 or 1.
If the input is any other number (positive only) then we do recursion.

The recursion is when we multiply the present number by the previous number and run the same function with this new result that we have.

For example, try a dry run on your won for 5,



See how it works for n=3

Iteration 1 in the function

3 != 1 or 0, so else case

 return 3*factorial(2) 

 2 != 1 or 0, so else case

return 3*2*(factorial(1)) 

1 == 1, so if-case

return 3*2*1 = 6

So this is the logic behind the code.

Here is the code, have fun, mess around and see what new things you can find in this. 

#include<bits/stdc++.h>
using namespace std;
int factorial(int n)
{
    if(n==1||n==0)
        return 1;
    else
        return n*factorial(n-1);
}
int main()
{
    int n;
    cin>>n;
    
    int nfinal = factorial(n);
    cout<<endl<<nfinal;
}

Comments