Monday, June 10, 2013

C# Recursive Method Call

A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int factorial(int num)
        {
            /* local variable declaration */
            int result;

            if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                return result;
            }
        }
    
        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            //calling the factorial method
            Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
            Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
            Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
            Console.ReadLine();

        }
    }
}
When the above code is compiled and executed, it produces following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

5 comments: