How do I convert a simple loop to use recursion?
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 recur开发者_如何学JAVAsive 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.
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.
精彩评论