Latest courses

C Program for Tower of hanoi

In this tutorial, we learn about tower of hanoi a mathematical game or puzzle, also see the c program using recursion, rules to find solution, application, and graphical representation.
It consists of a number of disks of different sizes which can slide on any of three rods(pegs). The game starts with the disks arranged in ascending order in the stack on one rod but makes sure the smallest at the top all-time and thus making a conical shape as shown in the below image.

c program for tower of hanoi

Some rules for game/puzzle to move the whole entire stack to another rod, Rules to move all disks over to 3 towers but you can not place a larger disk on a smaller disk. 


  1. Only one disk moves at a time.
  2. Only the "top" disk can be removed.
  3. In each movement taking the top disk from one tower to top of another tower but you can not place larger on a smaller disk.
With three disks, the game or puzzle can be solved in seven moves. The minimum number of moves required to solve a tower of hanoi is 2n-1, where n is the number of disks.

Below I shared graphical representation for tower of hanoi. so, it is easy for you to understand the mathematical puzzle.

Tower of Hanoi in C

Tower of Hanoi in C

Here I shared tower of hanoi c program using recursion for mathematical game/puzzle.

Source Code 


void hanoi(int n, char source_rod, char dest_rod, char aux_rod);

void main()


 int n;

 printf("Enter Number of Disks:\t");


 hanoi(n, 'A', 'C', 'B');



void hanoi(int n, char from_rod, char to_rod, char aux_rod) 




      printf("Wrong Number of disk\n");


    else if (n == 1) 


        printf("\n Move disk 1 from %c to %c", from_rod, to_rod); 





    hanoi(n-1, from_rod, aux_rod, to_rod); 

    printf("\n Move disk %d from %c to %c", n, from_rod, to_rod); 

    hanoi(n-1, aux_rod, to_rod, from_rod);




Enter Number of Disks:  3

 Move disk 1 from A to C

 Move disk 2 from A to B

 Move disk 1 from C to B

 Move disk 3 from A to C

 Move disk 1 from B to A

 Move disk 2 from B to C

 Move disk 1 from A to C


In above article, we learn the tower of hanoi in c using recursion, rules to find the solution, application, and graphical representation.

1 comment:

If you have any doubts, Please let me know

Powered by Blogger.