Pages

Ads 468x60px

Featured Posts

Saturday, June 14, 2014

Recursion Concept

Recursion is a simple yet powerful concept . Recursion is the process in which the function keeps calling itself (with possibly a different set of arguments) till some base condition is met.




Common example : factorial.

Find the factorial of a number using recursion

public static long Factorial(long number)
{
    // base condition - if the number is 0 or 1, return 1
    if (number <= 1)
        return 1;
    else
    {
        // recursive call to get the factorial again
        return number * Factorial(number - 1);
    }
}

As you can see in the above example, there is a base condition that allows the recursive call to terminate and then there is the recursive call itself. 

Fibonacci sequence :

public static int GenerateFibonacci(int count)
{
    if (count <= 1)
        return 1;
    else
        return GenerateFibonacci(count - 1) + GenerateFibonacci(count - 2);
}

 
 
Blogger Templates