# Someone explain this to me

• 10-12-2008
bigmac(rexdale)
Someone explain this to me
how does this work:
Code:

```#include <stdio.h> int fact(int n){   static int num = 0;   if(n == 1)     return 1;   else{     num++;     printf("&#37;d \n", num);     return fact(n-1)*n;   } } int main(void){   printf("fact(%d) is %d\n", 5, fact(5));   return 0; }```
i dont understand it to good, the return fact(n-1)*n; part
• 10-12-2008
nonoob
It's an example of recursion. A function calls itself, or it could have several levels: function A calls function B which calls function A.

If you call fact() with 0 or a negative value you're going to have a runaway condition. Otherwise the code looks OK on quick inspection. I haven't compiled it to check.
• 10-12-2008
bigmac(rexdale)
i dont understand how it works though, does it do n-1 = 4 * 5 = 20 the first time? if so what does it do the second time?

i put the static int num to see how much times the function is used but i still dont entirely understand how it works
• 10-12-2008
nonoob
Output:
Code:

```1 2 3 4 fact(5) is 120```
Yes. It is in fact doing 5 * 4 * 3 * 2 * 1
which is 120.

That's the definition of factorial.
Mathematically written it's 5! = 120
• 10-12-2008
bigmac(rexdale)
oh, makes sense now
• 10-12-2008
nonoob
Excellent! You get the idea.

I was wrong with the above - because it's not 100&#37; accurate reading it left-to-right.

In fact it's doing it in this order
(((1 * 2) * 3) * 4) * 5

Because factorial is defined as n x (n - 1) in short-form mathematical terms, it's used often to introduce recursive function calls in programming. Ironically it's probably the worst example of the need for recursion because a simple loop with a count-down is much more efficient.

Still, it expands the mind as to possibilities wherein recursion may serve elegantly with other problems.