pgubook-readers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Pgubook-readers] Re: Pgubook-readers Digest, Vol 6, Issue 1


From: Jonathan Bartlett
Subject: Re: [Pgubook-readers] Re: Pgubook-readers Digest, Vol 6, Issue 1
Date: Fri, 1 Oct 2004 13:45:19 -0700 (PDT)

> >However I'm stuck at chapter four on Recursive Functions, can anyone
> >explain this example in details. I get the main ideƩa but really don't
> >understand how the computer handles the function part.
> >

> >
> okey, so I have experimented some more... Is this right:
> %eax first become 3 then 2  (multiply these two values = 6) and then 1
> (total 6) so when the code after the second factorial call is beeing
> used %eax = 6 and 8(%ebp) later to be %ebx is 4. Is this right? Probably
> not, however it's this step I don't understand?
>

I'm not quite sure I understand your question.  Basically, %eax starts off
at 4.  It then suspends the current function to call itself with a lower
value, and calls itself w/ 3.  It then suspends itself and calls itself w/
2, it then suspends itself and calls itself with 1.  1 is the base case,
and we know that the factorial of 1 is 1.  So then you re-activate the
procedures before it with your results.  2*1 is 2.  Now we go back to the
previous function - 2 * 3 is 6.  Now we go to the previous function - 6 *
4 is 24.  Look at it like this:

factorial of 4 =

  4 * factorial(3) -- BEFORE we can answer this we have to find factorial(3)

factorial(3) =
  3 * factorial(2) -- BEFORE we can answer this we have to find factorial(2)

factorial(2) =
  2 * factorial(1) -- BEFORE we can answer this we have to find factorial(1)

factorial(1) =
  1

  Now we can finish the answers to our previous equations: 2 * 1 = 2.  2 *
3 = 6.  6 * 4 = 24.

The way that the computer keeps track of the state of the previous
functions is through the stack.  Each call to factorial moves the stack
pointer to a new location, so each call has its own parameters.

Jon




reply via email to

[Prev in Thread] Current Thread [Next in Thread]