From: Panagiotis Atmatzidis Date: 2010-01-04T01:53:44+09:00 Subject: Re: Few clarifications on recursion --Apple-Mail-2-762574964 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=utf-8 Hello On 03 =CE=99=CE=B1=CE=BD 2010, at 6:46 =CE=BC.=CE=BC., Josh Cheek wrote: >>=20 >> Although it introduces many interesting concepts to me (i. e. I did = not >> knew that after the "if" statement a single _1_ with no quotes could = be >> used) I fail to see how the num changes value. The way I read the = code here: >>=20 >>=20 > In Ruby, the last line of a function is returned. In this case, the = last > line is the if statement. The if statement evaluates to the last line = of > code inside of it. This means that if the number is less than or equal = to 1, > the last line of the if statement will be 1, so that is what the if > statement will evaluate to, and thus that is what the function will = return. Okay returns the last statement, but is it a number or a string? >=20 >=20 >> num * factorial(num-1) >>=20 >> is 30*29 for "puts factorial(30)" not 30*29*28... which is how it = works. >> I've tested the code works fine. >>=20 >>=20 > This is the recursive portion, it is not 30*29, it is = 30*factorial(29), and > factorial(29) is 29*factorial(28) and factorial(28) is = 28*factorial(27) > etcetera until you get to 1, and factorial(1) is just 1, because it is = less > than or equal to 1. >=20 > If you expand these calls out, you get 30*( 28*( 27*( ... *(1) ) ) ) >=20 >=20 > If you are still confused by this, try going the other way. Start with = 1, > and go up. If factorial(1) returns 1, what will factorial(2) return = (go > through the code)? And then what will factorial(3) return? And so on. Yes you are right. Now I get it. Thank you for pointing this out for = nicely! So this is the whole point of recursion to run the program (backwards in = this case) until the even that will stop the recursion happens. Thanks to all & regards Panagiotis (atmosx) Atmatzidis email: atma@convalesco.org URL: http://www.convalesco.org GnuPG ID: 0xFC4E8BB4=20 gpg --keyserver x-hkp://pgp.mit.edu --recv-keys 0xFC4E8BB4 -- The wise man said: "Never argue with an idiot. They bring you down to = their level and beat you with experience." --Apple-Mail-2-762574964--