Sunday, December 23, 2012

Recursive 2

previous post

We've been talking a bit about recursive, and we're still wondering how to stop the recursive. Now we're talking about it. I have another case for an example. 
Remember this operator in math. Yes, it is factorial. If I have 3!, what's the result? 6 of course. That's too easy. But, I want to ask you, how did you find 6 from 3!? 

3! = 3 * 2 * 1
    = 6
Okay. That's correct. Now, what about 2!

2! = 2 * 1
    = 2

Can I replace some parts in 3! equation with 2! ? See the red-colored text. 

3! = 3 * 2 * 1
    = 3 * 2!

You should have got a clue about the recursive. You don't? It's actually a recursive. If you want to know the result of 3! you need to find 2! . In general we can say that to find x! you need to find (x-1)! 

X! = (X-1)!

If you've got the recursive idea, let's write it as code. This is the factorial function. 


int factorial(int n)
{
    return n * factorial( n-1 ); 
}

int main()
{
   int result = factorial(3);
   printf("%d\n",result);
   return 0;
}


You can see the recursive is working in that code. Now, we're getting to the main topic in this chapter, which is how to stop the recursive method. In our case, the factorial will end when it meets 1. What we need to do, is add a conditional statement. We need to make a different action when it meets 1 as n. See the example below.



int factorial(int n)
{
    if(n == 1)
        return n;
    else 
        return n * factorial( n-1 ); 
}

int main()
{
   int result = factorial(3);
   printf("%d\n",result);
   return 0;
}


If you understand this things, let's move on to a more interesting example. We'll use recursive to make some 2D AI. On the next chapter of course. :)

next post

No comments:

Post a Comment