Hi freinds,
this is my code for simple recursion program to calculate factorial.
wheneve i return the different value for eg,
1.for return 1, the ans will be 720, which is correct one.
2.for return 0, the ans will be 0.
3.for return 2, the ans will be 1440.
#include<iostream>
using namespace std;
int factorial(int no)
{
if(no==1)
return 1;
//return 0;
//return 2;
else
return (no * factorial(no-1));
}
int main()
{
cout<<"Fatorial is "<<factorial(6);
}
yes, i knew that. but when you call the function you will put ' if(n>=0) factorial(n); ' and else print 'put positive number or 0'. then the program will be ok..
Grey Wolf
Hi,
thats my code and i know that how recursion works.
But i just want to know why last value returned is also get multiplied with final answer..
for e.g
return 2;
The last value returned, as you put it, is actually the first value returned.
If you call factorial(2) it wants to return 2 * factorial(2 - 1), so it calls factorial(2 - 1). As this is 1! it has to return 1 (anything else is wrong*). If you do return 2 to the previous caller that would return 2*2 = 4.
3! = 3 * 2!
= 3 * 2 * 1!
= 3 * 2 * 1
* You could call factorial(0) but that would result in a pointless function call and multiplication operation as 0! is also 1.