This program demonstrate Tower of Hanoi in C#. Tower of Hanoi is a mathematical riddle algorithm. It consists of three rods and rollers of different sizes that can slide into any rod. The puzzle starts with discs in a smooth stack of increasing size on a smallest bar at the top. It is a game that we get the same stack on the other bar.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Program { /* n: number of disks used D: Starting location A: arrival location I: intermediate location */ static void tourHanoi(int n, char D, char A, char I) { if (n == 1) Console.Write("Disc 1 from {0} to {1} \n", D, A); else { // D to A tourHanoi(n - 1, D, I, A); Console.Write("Disc {0} from {1} to {2} \n", n, D, A); //I to A // Console.Write((n - 1, I, A, D); } } static void Main(string[] args) { int nDisques = 3; tourHanoi(nDisques, 'A', 'B', 'C'); Console.ReadLine(); } } |
Output: