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
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
Share on other sites

  • 3 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.