(C#) Tower Of Hanoi

Posted: July 30, 2008 in C#, Programming
Tags: ,

Hello again, now, for killing time in holiday,i wrote a program again :) , the program is Tower Of Hanoi. Here sort explanation of Tower Of Hanoi, i took it from Wikipedia:
The Tower of Hanoi or Towers of Hanoi (also known as The Towers of Benares) is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks neatly stacked in order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

  • Only one disk may be moved at a time.
  • Each move consists of taking the upper disk from one of the pegs and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  • No disk may be placed on top of a smaller disk.
  • Using recurrence relation, the exact number of moves that this solution requires can be calculated by: 2h − 1

here the code written in C#:

using System;
using System.Collections.Generic;
using System.Text;

namespace Hanoi
    class Program
        static void Main(string[] args)
            int x;
            char from='A', to='B', help='C';

                    Console.Write("  input number of disk: ");
                    x = Int32.Parse(Console.ReadLine());
                catch (FormatException e)
                    x = -10;
            }while(x==-10 || x>10);
            Console.WriteLine("n  from = A, to = B, help = Cn");
            hanoi(x, from, to, help);


        static void hanoi(int x, char from, char to, char help)
            if (x > 0)
                hanoi(x - 1, from, help, to);
                move(x, from, to);
                hanoi(x - 1, help, to, from);


        static void move(int x, char from, char to)
            Console.WriteLine("  move disk "+x+" from "+from+" to "+to);


  1. raied says:

    please can you help me in hanoi tower with explaining the code in C#

  2. azer89 says:

    try to thinking recursive… :)

  3. kristine marie says:

    hi, just wondering if you have the web forms application for towers of hanoi?

  4. xuan says:

    is there any way of solving hanoi without a recursive algorithm ?

  5. Hanna says:

    thank you :-)

  6. Aegloss says:

    I saw this article on Code Project, with similar code for you hanoi method and a nice UI done in windows forms. http://www.codeproject.com/Articles/393158/Towers-of-Hanoi

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s