When fatorial
is called within:
return $num*fatorial($num-1);
The
$num
is subtracted by
-
(in
fatorial($num-1)
), then the
$num
that started with
5
on the next call will be
4
, when it reaches
fatorial($num-1);
-1
again.
As ($num-1)
has the value of 1
when calling fatorial()
, it will enter its if
, which compares if $num
is equal to 1
%, then at this point the return
"premature" will occur, which will end the function inside the if
, which will return the current value return $num;
which in this case is 1
itself.
Then the process will look like this:
- The input will be
5
- ignores
if ($num == 1)
-
The return "5 multiplies by fatorial(5-1)
"
-
The input will now be 4
(before finishing multiplication)
- ignores
if ($num == 1)
-
The return "4 multiplies by fatorial(4-1)
"
-
The input will now be 3
(before finishing multiplication)
- ignores
if ($num == 1)
-
The return "3 multiplies by% with%"
-
The input will now be fatorial(3-1)
(before finishing multiplication)
- ignores
2
-
The return "2 multiplies by% with%"
-
The input will now be if ($num == 1)
(before finishing multiplication)
- Enter%% of%
- The return will return the value of
fatorial(2-1)
, which according to 1
is expected if ($num == 1)
(will occur the $num
"premature" I mentioned)
Now the rest of the back process (recursion) occurs: