Click here to Skip to main content
15,888,610 members
Articles / Programming Languages / C#

Recursion made simple

Rate me:
Please Sign up or sign in to vote.
4.60/5 (42 votes)
27 Jul 2012CPOL11 min read 223.5K   3.1K   101  
An introductory tutorial on recursion technique using C#.NET
namespace Recursion
{
    //Tower of Hanoi Example
    //Tower of Hanoi problem: Given three pegs, one with a set of N disks of increasing size, 
    //determine the minimum (optimal) number of steps it take to move all the disks from their 
    //initial position to another peg without placing a larger disk on top of a smaller one.
    class TowerofHanoi
    {
        static int depth;
        public TowerofHanoi() { }
        public int DoDiskMovements(int disks)
        {
            depth++;
            if (depth == 1)
            {
                if (disks <= 0)
                    return 0;
            }
            if (disks == 1 )
            {
                return 1;
            }
            else
            {
                return 2 * DoDiskMovements(disks - 1) + 1;
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Working as Senior Developer in US based MNC. Interested in R&D, writing/reading techinical articles, sci-fi movies, playing synthesizer.

Comments and Discussions