1. ## Recursive function behaviour

I have got following code.
PHP Code:
``` \$x = 1; \$y = 3; function func(\$x, \$y){     if(\$x <= 0){                  return \$y;     }     else{         return 1+func(\$x-1,\$y);     } } echo func(\$x, \$y);  ```
Can some one explain that how and why it is showing " \$x+\$y " result.

2. Because... that's what your function does.

You recurse down until X = 0. Return Y, and then for each level of X you recursed down, you add 1. Which, is in effect, x+y.

3. Originally Posted by dr_dumb99
Can some one explain that how and why it is showing " \$x+\$y " result.
\$x = 1, \$y = 3
...
return 1 + func(0, 3)
= return 1 + 3

\$x = 2, \$y = 4
...
return 1 + func(1, 4) where func(1, 4) equals 1 + func(0, 4)
therefore
return 1 + (1 + func(0, 4))
= 1 + 1 + 4
= 6

4. How \$x+\$y. It is creating confusion.

5. Do what computer programmers are taught from the beginning.
Get out a pen and paper, draw 3 columns at the top. label 1 \$x, 1 \$y, and 1 ReturnValue.

I have a feeling we're being asked to do someone's homework here.

6. Originally Posted by dr_dumb99
How \$x+\$y. It is creating confusion.
Each time it drops \$x by 1, it returns 1 + \$y
The more times it drop \$x by 1, the more times it return 1 + \$y

Code:
```\$x = 2, \$y = 3
func(\$x, \$y) is a call to func(2, 3)
When you call func(2, 3) the function calls func(1,3)
When func(1, 3) is called, it calls func(0, 3)
When func(0, 3) is called, it returns 3
When func(1,3) gets the returned 3, it returns 1 + 3, which is 4
When func(2,3) gets the returned 4, it returns 1 + 4, which is 5.```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•