exo_1
exo_1

Reputation: 41

recursion using for do loop (pascal)

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

Answers (1)

Wosi
Wosi

Reputation: 45243

There are several problems in your code.

  1. First of all it doesn't compile because you are accessing the undefined variable j.
  2. 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?

enter image description here

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;

Upvotes: 2

Related Questions