**C program for tower of hanoi** is a simple and easy puzzle.

**Tower of hanoi in c** is a game program in c.

In this tutorial we will send what is tower of hanoi, how tower of hanoi works, C program for tower of hanoi.

**Tower of hanoi**

Tower of hanoi is puzzle and mathematical puzzle which contains 3 rods with disks placed on then from largest to small and we need to move disks from source to destination using temporary rod.

**How tower of hanoi works**

**Tower of hanoi game**

We have 3 rods (tower) . And disks with different sizes arranged on rod in ascending order such that largest one is on bottom.

The mission is to move all the disks to some another tower without violating the sequence of arrangement.

**Tower of hanoi rules**

1. Only one disk is moved from rod at a time

2. No large disk can be placed on small disk

3. Only top most disk can be moved.

**Tower of hanoi example**

1. Take 3 pegs (tower)

2. First, we move the smaller (top) disk to aux peg.

3. Then, we move the larger (bottom) disk to destination peg.

4. And finally, we move the smaller disk from aux to destination peg.

**Tower of hanoi algorithm**

1. Start

2. Take 3 peg (source, destination, auxiliary)

3. Move n-1 disks from source to aux

4. Next Move nth disk from source to dest

5. Move n-1 disks from aux to dest

## Tower of hanoi in c

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> void towerOfHanoi(int,char,char,char); main() { int n; printf("Enter no of disks\n"); scanf("%d",&n); towerOfHanoi(n, 'A', 'C', 'B'); } void towerOfHanoi(int n, char from, char to, char temp) { if (n == 1) { printf("Move disk 1 from %c to %c\n", from, to); return; } towerOfHanoi(n-1, from, temp, to); printf("Move disk %d from %c to %c\n", n, from, to); towerOfHanoi(n-1, temp, to, from); } |

**Output :**

**Explanation :**

**1. First we declare function which is to move pegs from peg.**

**2. Write main function**

**3. Declare variable**

n => to store number of disks

**4. Take disk input from user**

scanf(“%d”,&n);

=> n = 2

**5. Pass 2 disk input to function**

towerOfHanoi(2, ‘A’, ‘C’, ‘B’);

**6. Execute function**

if (n == 1) => condition false

**Move disk from A to B**

=> towerOfHanoi(1,’A’,’B’,’C’)

Move disk from temp to destination

=> towerOfHanoi(1,’B’,’C’,’A’)

**Move disk from A to B**

=> towerOfHanoi(1,’A’,’B’,’C’)

**Move disk from C to A**

=> towerOfHanoi(1,’C’,’A’,’B’)

**Move disk from B to C**

=> towerOfHanoi(1,’B’,’C’,’A’)

**Move disk A to C**

=> towerOfHanoi(1,’A’,’C’,’B’)

**7. Print moves as to move disk**

printf(“Move disk %d from %c to %c\n”, n, from, to);

## Leave a Reply