1

So I have this code:

WRITELN( “input which member of series”) 
READ(n)
p ← 2
prev1 ← 1
prev2 ← 1
WHILE p IS LESS THAN n DO 
BEGIN
term ← prev1  +  prev2
prev2 ← prev1 
prev1 ← term 
p  ← p  +  1
END 
WRITELN (“term  =”, term)

Can someone help me rewrite the code so it works recursively (in either PHP or Pascal).

EDIT

N = 4

I'm using PASCAL. The problem is, the non-recursive code returns 3, while the recursive code returns 2.

This is my recursion code:

program Fibfun;

VAR
n,prev1,prev2,term : Integer;

FUNCTION sw(p:integer):integer;Begin
  if p < n then
      Begin
         term:= prev1 + prev2;
         prev2:=prev1;
         prev1:=term;
      End
  else
  Begin
   p:= 1 + sw(p);
   End;
sw:=term;
End;

Begin
prev1:=1;
prev2:=1;
term:=1;
writeln('Input number: ');
readln(n);

writeln('term ', sw(2));

readln;
End.
Laurel
  • 5,965
  • 14
  • 31
  • 57
Mifas
  • 21
  • 3
  • 1
    You should read what recursion is to fully understand it... should read what recursion is to fully understand it... should read what recursion is to fully understand it... http://www.google.com/search?sclient=psy&hl=en&source=hp&q=recursion&pbx=1&oq=recursu&aq=2sL&aqi=g-L2g-sL1g-L2&bav=on.2,or.r_gc.r_pw.&biw=1920&bih=967 – daGrevis Aug 02 '11 at 07:32
  • http://stackoverflow.com/questions/717725/understanding-recursion – daGrevis Aug 02 '11 at 07:40
  • yes. I put my recursion code but this is not wordking – Mifas Aug 02 '11 at 07:41
  • Ok i get the answer the increment part it must inside the if condition 'FUNCTION sw(p:integer):integer;Begin if p < n then Begin term:= prev1 + prev2; prev2:=prev1; prev1:=term; p:= sw(p + 1); End; sw:=term; End;' – Mifas Aug 02 '11 at 07:50
  • Is this the fibonacci series ? – opc0de Aug 02 '11 at 09:12

1 Answers1

0
program test;     
var
 result : longint;
 num,i, error: integer;
 strnum: string;

function fib(n : integer) : longint;
begin
    if n <= 2 then fib := 1
    else fib := fib(n-2) + fib(n-1);
end;

begin
if ParamCount = 0 then
begin
  writeln('Enter integer:');
  readln(strnum);
  val(strnum,num,error);
end else 
begin
 val (ParamStr(1), num, error);
end;
for i := 1 to num do
begin
  result:= fib(i);
  writeln(i, ' : ', result);
end;

end.
opc0de
  • 11,557
  • 14
  • 94
  • 187