Translate

Tuesday, July 2, 2013

c# recursion tutorial

A recursive function is one that calls itself over and over until a certain condition is met. Once that condition is met, it exits.

An example of Recursion in C#

using System;

namespace ConsoleApplication3
{
    class Test
    {
        static void Main()
        {
            Console.WriteLine(factorial(4));//24
        }

        static int factorial(int x)
        {
            if(x==1)
            {
                return 1;
            }
            return x*factorial(x-1);
        }
    }

}




A more complicated problem where recursion makes it easier to solve is the Towers of Hanoi problem. This is taught in many computer science programs.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator