There are several problems in your code.
- First of all it doesn't compile because you are accessing the undefined variable
j.
- Calculating the factorial using a loop is the iterative way of doing it. You are looking for the recursive way.
What is a recursion? A recursive function calls itself. So in your case calculateFactorial needs a call to itself.
How is the factorial function declared?

In words:
The factorial of n is declared as
- 1 when
n equals 0
- the factorial of
n-1 multiplied with n when n is greater than 0
So you see the definition of the factorial function is already recursive since it's referring to itself when n is greater than 0.
This can be adopted to Pascal code:
function Factorial(n: integer): integer;
begin
if n = 0 then
Result := 1
else if n > 0 then
Result := Factorial(n - 1) * n;
end;
No we can do a few optimizations:
- The factorial function doesn't work with negative numbers. So we change the datatype from
integer (which can represent negative numbers) to longword (which can represent only positive numbers).
- The largest value that a
longword can store is 4294967295 which is twice as big as a longint can store.
- Now as we don't need to care about negative numbers we can reduce one
if statement.
The result looks like this:
function Factorial(n: longword): longword;
begin
if n = 0 then
Result := 1
else
Result := Factorial(n - 1) * n;
end;
jisn't declared anywhere. Also,Anever changes in your loop, thereforej(fromj := A-1never changes, and, therefore,A*jnever changes. Your factorial program returnsA*(A-1). - lurkerA*calculateFactorial(A-1), no loop necessary. - D. Ben Knoble