Pages

Thursday 17 July 2014

Recursion using C#

A Recursive method/function calls itself, until the condition set becomes True. The recursive algorithm is used to solve complex problems. Though it is not used that much, but one should know how to use it if the need arises.




Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Recursive_Calling
{
    class Program
    {
        public int factorial(int n)   //A function of integer datatype is created called factorial which accepts a                                                                    parameter of an integer number.
        {
            int r;  //result

            if (n == 1)  //condition is set to 1
            {
                return 1;
            }
            else
            {
                r = factorial(n - 1) * n;   //formula for calculating factorial
                return r;
            }
        }


        static void Main(string[] args)
        {
            Program p = new Program();   //instance of Program class is initialized
            Console.WriteLine("factoral of 3 is: " + p.factorial(3));  //factorial method is accessed using the                                                                                                                     instance of Program class.
         
            Console.Read();                //to stop window from closing.
        }
    }
}

Output:
Factorial of 3 is: 6

No comments:

Post a Comment