Recursion

Recursion is a process where a method calls itself repeatedly until it arrives on a desired value. Recursion is a complex topic in programming and mastering it is not that easy. Recursion must stop at some point or else, it will call itself for an infinite number of times. For this lesson, I will show a very simple example of recursion.The factorial of a positive whole number n (denoted as n!) is that the product of all positive integers but or capable n. contemplate the factorial of five.

5! = 5 * 4 * 3 * 2 * 1 = 120

So to make a recursive method, we need to analyze how our method will stop its recursion. Based on the description of recursion, the factorial only accepts a positive integer. The lowest positive integer we can give is 1. We will use this value to stop the recursion.

using System;

namespace FactorialDemo
{
    public class Program
    {
        static long Factorial(int number)
        {
            if (number == 1)
                return 1;   


            return number * Factorial(number - 1);
        }

        public static void Main()
        {
            Console.WriteLine(Factorial(5));
        }
    }
}

Example 1 – Factorial Using Recursion

120

The method returns a long value because factorial calculations can be very big. The method accepts one argument which is the number that will be involved in the calculation. Inside the method, we first wrote an if statement  in line 9 telling that if the argument provided is equal to 1, then we will return 1 as the value. If it is not 1, then we will proceed in the next line.  This condition is also the one that will determine if the repetition of calls  should stop. Line 12 multiplies the current value of number and then the method calls itself providing an argument which 1 less than the current value of number. Inside the method called inside the original method, processes will again occur, and if the argument passed is not equal to 1, then it will do another recursive step. The diagram below shows the how we arrived at the final value.

The above code can be rewritten using a for loop.

factorial = 1;

for ( int counter = number; counter >= 1; counter-- )
   factorial *= counter;

The above code is easier than its equivalent code that uses recursion. Recursion has its specific use in the field of computer science. Recursion is used when it seems more natural to use it than using a non-recursion version (called Iteration). Recursion consumes more memory so do not use recursion if speed is important.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *