today 1st time i’m trying to learn recursive function thru online tutorials but stuck at beginning stage. i found below code but its provide me ‘output: 1’ against any value.
so, i need better explanation of that:
function factorial($n){
if($n==0){
return 1;
}
return fact($n, 1);
}
function fact($i, $j){
if($i<1){
return 1;}
else {
return fact($i-1, $i*$j);
}
}
echo factorial(5);
one more thing, i need clarification of how below return method:
return fact($i-1, $i*$j);
will work to convey single value from two parameters. any1 plsss give me some ideas regarding this issue to clear my concept. Thnx in advance..
You have a function
factorialhere that calls a recursive functionfact. A recursive function always works like this:If you call it with a “trivial” argument, it can immediately give you the answer. In your code, that is the part saying
if($i<1){ return $j; }(As per the comment of @Sreenath)If the argument is more “complicated”, the function simplifies the argument (that is
$i-1in your example: The trivial case is$i<1, so making$ismaller makes the argument easier in some way) and then calls itself with the simpler argument and possibly some additional information, which is where thefact($i-1, $i*$j)call comes from.So the recursive function
facthere works doing the following thing:Now if you want just the factorial, you need to call
factwith1as second argument, just as you do inreturn fact($n, 1);.