pascal functions - Programmers Heaven

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# pascal functions

Posts: 3Member

1 function fun(x:Integer):Integer;
2 begin
3 if x > 100 then
4 fun:=x-10
5 else
6 fun:=fun(fun x+11)
7 end;

hey guys am pretty new to pascal. Can you please explain me what line 6 does.. and if it is wrong then please correct me

• Posts: 438Member
It's wrong. The compiler is going to expect a left parenthesis after the identifier "fun." I'm guessing that it should be as I've changed it below.

In line 6 the function calls itself recursively. If passed a number <= 100 it will repeatedly increase that number by 11 until it is > 100, then subtract 10 and return.
[code]
function fun(x : Integer) : Integer ;
begin
if x > 100 then
fun := x - 10
else
[red]fun := fun(x + 11)[/red]
end ;
[/code]
For example, if passed 88 it will call itself and return 99. That's still <= 100 so it calls itself again and returns 100. That's > 100 so on the final call to itself it subtracts 10 and returns 100.

The intended code may be:
[code]
[red]fun := fun(fun(x + 11))[/red]
[/code]
• Posts: 3Member
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
• Posts: 438Member
: 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
:
[code]
function fun(x : Integer) : Integer ;
begin
if x > 100 then
fun := x - 10
else
[red]fun := fun(fun(x + 11)) {line 6}[/red]
end ;
[/code]
The important thing to grasp about line 6 is that the function calls itself, a process called [b]recursion.[/b]

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.