Jump to content

recursion help


mpsn

Recommended Posts

seriously, jokes aside, let's say i have this eg:

 

void printnum ( $begin )

{

  echo $begin;

  if ($ begin < 9 ) 

  {                         

      printnum ( $begin + 1 );

  }

  echo $begin;       

                             

}

 

let's say $begin is 5, it will output: 5678998765

 

I don't understand how it knows to do the decrementing?

 

 

Link to comment
https://forums.phpfreaks.com/topic/253036-recursion-help/#findComment-1297325
Share on other sites

There isn't any decrementing; $begin only goes up.

 

There's three parts to the function:

1. Print $begin

2. Maybe call printnum with $begin+1

3. Print $begin

 

Between steps 1 and 3 $begin does not change. It's still the same value as before because the two functions are running with different sets of variables. So if $begin is 5 the function will print

5 stuff 5

The "stuff" is whatever printnum($begin+1) prints.

 

printnum(5) | printnum(6) | printnum(7) | printnum( | printnum(9)
------------+-------------+-------------+-------------+------------
print 5    |             |             |             |
           -->            |             |             |
            | print 6     |             |             |
            |            -->            |             |
            |             | print 7     |             |
            |             |            -->            |
            |             |             | print 8     |
            |             |             |            -->
            |             |             |             | print 9
            |             |             |             | print 9
            |             |             |                        |             |             | print 8     |
            |             |                        |             | print 7     |             |
            |                        | print 6     |             |             |
            print 5    |             |             |             |

Link to comment
https://forums.phpfreaks.com/topic/253036-recursion-help/#findComment-1297326
Share on other sites

  • 3 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.