Anang M
Anang M

Reputation: 149

Pascal basic, need some explanation

Recently i just started learn pascal then i found this code

function mengkono(s: integer):integer;
begin
  if s < 3 then
    mengkono := 3*s+1
  else
    mengkono := mengkono(s-1) + megnkono(s-2);
end;

begin
  writeln(mengkono(6));
  readln;
end.

the thing that confused me is this line

else
  mengkono := mengkono(s-1) + mengkono(s-2);

from the code above, it's output is 47. Because the input is 6 and 6 is greater than 3 so the line above is ran. Can someone explain to me how it works? i still confused.

Upvotes: 1

Views: 70

Answers (2)

J_P
J_P

Reputation: 781

This is a recursive function. A function that calls to itself.

If the input is 6 then first it'll do megnkono:=megnkono(5)+megnkono(4)

then you need to caclulate megnkono(5) and megnkono(4) for 5 it'll be megnkono:=megnkono(4)+megnkono(3) then you need to caclulate megnkono(4) and megnkono(3)

and so on... (pay attention when input is <3 is just giving a direct result)

Upvotes: 1

Abra
Abra

Reputation: 20914

The function is a recursive function, i.e. it calls itself (the line that confuses you). Every time that line executes, s is slightly smaller and eventually it goes below 3 which stops the recursion.

Upvotes: 1

Related Questions