Guys ... I was trying to figure it out
how does this statement (else return 1;)
doesn't make the condition passes through it and give the whole function the value (1) at the end of time,
well, it does! the function, WHEN THE PARAMETER IS 1, RETURNS 1. The whole value of the function, in that call, is one, yes. What you are not seeming to get is that the function is called many times. In some of the calls, it is NOT called with 1, and it returns a different number.
again, in reverse, its called with 1. it returns 1. That resumes the call when it was 2, so it takes the value 1, multiples it by 2, and returns 2. The two returns to when it was called with 3, multiples 3*2, and returns 6. and so on until it backs all the way up to the original call (5 in my examples).
the function calls of recursion are distinct.
its as if you said
for(x = 1; x <=5; x++)
y *= foo(x);//foo is called several times in this loop. the result of foo(1) has not effect on the result of foo(5), right? Recursion is the same way. The fact that it happens to call itself is irrelevant, each call is still independent.
Upper level math does touch recursive definitions of some series and the like, but more or less recursion is not a math thing. Its doing math here, but you could just as easily reverse a string with it (recursion is good at reversing things, note how it is multiply in reverse in your factorial).
1 2 3 4 5 6
|
char cs[] = "hello world";
void rev(char* c)
{
if(*c) rev(c+1);
cout << *c;
}
|
is the letter the 0 terminating letter of a c-string? nope, its h. call it with e. is e the 0? nope, call it with l, l, 0, space, w, o, r, l,d, there is is, cout the 0 null char (which will look like a space in a console window, this is a quick lazy example so ignore that), cout the d,l,r,o,w,space,o,l,l,e,h …
it takes a little time to really 'get' recursion. Once you see it, you will be fine. It lets you write small functions that do things cleanly with a tiny bit of code that otherwise take much more code, so keep it in your toolbox. Also, think before you do: a factorial in a real piece of code would use a lookup table, not a computation. Its used to teach recursion because it is a simple example.
int fact[] = {1,1,2,6,24,120,720, ...};
..
result = fact[5]; //120