Recursivity

What is the function of this property? And may a example please be provided.
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
Your '+' should be a '*'.
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?
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
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
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.