Reputation: 41
I'm trying to use the concept of recursion but using for do loop. However my program cannot do it. For example if I want the output for 4! the answer should be 24 but my output is 12. Can somebody please help me?
program pastYear;
var
n,i:integer;
function calculateFactorial ( A:integer):real;
begin
if A=0 then
calculateFactorial := 1.0
else
for i:= A downto 1 do
begin
j:= A-1;
calculateFactorial:= A*j;
end;
end;
begin
writeln( ' Please enter a number ');
readln ( n);
writeln ( calculateFactorial(n):2:2);
readln;
end.
Upvotes: 2
Views: 927
Reputation: 45243
There are several problems in your code.
j
. 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
equals0
- the factorial of
n-1
multiplied withn
whenn
is greater than0
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:
integer
(which can represent negative numbers) to longword
(which can represent only positive numbers).longword
can store is 4294967295 which is twice as big as a longint
can store.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;
Upvotes: 2