: hey thank you very much
:
: i think the line 6 is
:
: fun:=fun(fun(x+11));
:
: So i still did not understand how that line executes. if supose the
: value of x is 95. can you please explain
:
function fun(x : Integer) : Integer ;
begin
if x > 100 then
fun := x - 10
else
fun := fun(fun(x + 11)) {line 6}
end ;
The important thing to grasp about line 6 is that the function calls itself, a process called
recursion.
If x = 95 the function jumps to the "else" part (line 6) where it calls itself twice, a double recursion. Call these recursions the outer and inner calls.
The inner call is passed x + 11 = 106 which is > 100, so it goes to the "then" part and returns 106 - 10 = 96, which becomes the argument of the outer call. Since 96 <= 100 the function again winds up at the double recursion, line 6.
The code is tricky. It's simple enough if x >100 but, if not, then it appears to go into recursion, increasing x by one each time until x = 101. It then subtracts 10 and ends by returning 91.
As you can see, recursion is actually a form of looping. In some cases (not this one) it can make code simpler. Its down side is that it tends to gobble up memory. For each level of recursion the function makes another copy of itself. In this example the program makes two additional copies of of "fun" each time through the loop. A low enough value of x, like - 32000, would probably consume all memory and the program would crash.
Since this function is named "fun" I assume that it's supposed to be a puzzler, but it's not the sort of thing that you'd want to put in a real program.