C# Program to Demonstrate Tower of Hanoi

What we are going to look at through this article is C# Program to Demonstrate Tower of Hanoi We will look at this in detail through this article.

We implement Demonstrate Tower of Hanoi. In this puzzle, there are three rods and several disks of different sizes. In this puzzle, the puzzle starts with a single rod, smaller at the top, with disks stacked in ascending order. Here we need to get the same layer on the 3rd wire.

C# Program to Demonstrate Tower of Hanoi

C# Program to Demonstrate Tower of Hanoi

main.cs

/*
 * C# Program to Demonstrate Tower Of Hanoi
 */
using System;
class TowerOfHanoi
{
    int m_numdiscs;
    public TowerOfHanoi()
    {
        numdiscs = 0;
    }
    public TowerOfHanoi(int newval)
    {
        numdiscs = newval;
    }
    public int numdiscs
    {
        get
        {
            return m_numdiscs;
        }
        set
        {
            if (value > 0)
                m_numdiscs = value;
        }
     }
     public void movetower(int n, int from, int to, int other)
     {
         if (n > 0)
         {
             movetower(n - 1, from, other, to);
             Console.WriteLine("Move disk {0} from tower {1} to tower {2}", 
                                n, from, to);
             movetower(n - 1, other, to, from);
         }
     }
}
class TowersOfHanoiApp
{
    public static int Main()
    {
        TowerOfHanoi T = new TowerOfHanoi();
        string cnumdiscs;
        Console.Write("Enter the number of discs: ");
        cnumdiscs = Console.ReadLine();
        T.numdiscs = Convert.ToInt32(cnumdiscs);
        T.movetower(T.numdiscs, 1, 3, 2);
        Console.ReadLine();
        return 0;
    }
}

Read Also:

C# Program to Build Snake Apple GUI Desktop Game

Final Thoughts

What we learned through this article is C# Program to Demonstrate Tower of Hanoi. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.    

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment