Recursivity

Dec 2, 2009 at 11:25pm
What is the function of this property? And may a example please be provided.
Dec 3, 2009 at 2:52am
It can make certain functions' design look more elegant. The well-known recursive factorial function looks like this:
1
2
3
4
unsigned int factorial(unsigned int num) {
   if(num <= 1) return 1;
   return num * factorial(num - 1);
}
Last edited on Dec 7, 2009 at 9:23pm
Dec 3, 2009 at 4:36am
Your '+' should be a '*'.
Dec 4, 2009 at 9:21pm
Hmm...

May you provide a example of recursive's equivalent? As in how the switch function is equivalent to if-eles function. Is the factorial function within a libary and what math fomula does the factorial function use?
Dec 4, 2009 at 9:27pm
Same as above without recursion:
1
2
3
4
5
6
7
8
9
unsigned factorial ( unsigned num )
{
    unsigned result = 1;

    for ( unsigned i = 1; i <= num; i++ )
        result *= i;

   return result;
}

A recursive function is a function which calls itself

see http://www.cplusplus.com/forum/articles/2231/
Last edited on Dec 4, 2009 at 9:29pm
Dec 23, 2009 at 4:24am
Hey,

In post 2 (Zhuge), in what scenario do you use the distributive property from math?

When I first viewed the source code, I thought that it meant:

return num * factorial(num - 1]

num * factorial(num) - factorial(1)

Thanks Bazzy for clearing up the recursive function.
Last edited on Dec 23, 2009 at 4:24am
Dec 23, 2009 at 8:39am
No, that doesn't work because functions are not just parentheses. They do things based on what their parameters are; for example, consider:

1
2
3
4
int myFunc(int a) {
     if(a == 5) return 100;
     else return 0;
}


1
2
myFunc(5 - 1); // == myFunc(4) == 0
myFunc(5) - myFunc(1); // == 100 - 0 == 100 
Topic archived. No new replies allowed.