program recursive_factorials;
var n, result : integer;
x : char;
function factorial (n:integer) : integer;
begin
if n=0 then
factorial := 1
else
factorial := n * factorial (n-1);
end;
begin
writeln ('Enter n for size of factorial to be found');
readln (n);
result := factorial (n);
writeln ('Answer is ', result );
readln (x);
end.
The function factorial calls itself until its input value is zero, at which point it returns zero and the previous calls are terminated. The previous answers to factorial:= are retrieved and the correct answer given. For example:
n=5:
factorial (5) gives factorial := 5 * factorial (4)
factorial (4) gives factorial := 4 * factorial (3)
factorial (3) gives factorial := 3 * factorial (2)
factorial (2) gives factorial := 2 * factorial (1)
factorial (1) gives factorial := 1 * factorial (0)
factorial (0) finishes the calls
The calls unwind in reverse order performing the multiplications as they go:
The result from factorial (0) is multiplied by the result from factorial 1 (1
* 1 = 1)
Then the result from factorial (1) is multiplied by the result from factorial
2 (1 * 2 = 2)
Then the result from factorial (2) is multiplied by the result from factorial
3 (2 * 3 = 6)
Then the result from factorial (3) is multiplied by the result from factorial
4 (6 * 4 = 24)
Then the result from factorial (4) is multiplied by the result from factorial
5 (24 * 5 = 120)
Note that beyond 16! results are unreliable: 17! returns a negative number: why?