[clug-progsig] Recursion (was Javascript how to write to a <textarea>)

Chris Berry chrisb at chrisbtoo.net
Fri Feb 25 10:48:45 PST 2005


Shawn wrote:
> That said, I can see why this is a confusing example - the function returns 
> "Add(x, y)", but the function only explicitly returns zero in the ending 
> condition, so I believe this sample would return zero all the way back up the 
> stack.  I could be wrong - I haven't tried to run the code.  But that's the 
> easiest way to see what might happen, or to test a theory - run it and see 
> what happens (save your work first though - just in case).

You're right, it returns 0, which percolates back up the call stack.

It should really return x:

int Add (int x, int y)
{
     if (y == 0) return x;

     if (y > 0) return (Add (x + 1, y - 1));

     /*if (y < 0)  - must be, as it's neither 0, nor > 0 */
     return (Add (x - 1, y + 1));
}

So:

  Add(4, 3) returns
   Add(5, 2) returns
    Add(6, 1) returns
     Add(7, 0) returns 7

and:
  Add(4, -3) returns
   Add(3, -2) returns
    Add(2, -1) returns
     Add(1, 0) returns 1

In each case, calls to Add(x,y) are returning the value they got back 
from their "child" call of Add(x+1,y-1), Add(x-1,y+1) or, in the bottom 
case, x.

Because the arguments to the function are passed by value, each x and y 
are local to the instance of the function that's running at the time.


Chris.




More information about the clug-progsig mailing list