C++ Program to Solve Tower of Hanoi using Binary Value

«
»
This C++ program displays the solution to the Tower of Hanoi problem using the base-2 representation of the move number with the following rules:-
There is one binary digit (bit) for each disk.
The most significant (leftmost) bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it’s on the final peg.
The bitstring is read from left to right, and each bit can be used to determine the location of the corresponding disk.
A bit with the same value as the previous one means that the corresponding disk is stacked on top the previous disk on the same peg.
A bit with a different value to the previous one means that the corresponding disk is one position to the left or right of the previous one.

Here is the source code of the C++ program to display the movement of disks from one peg to the other. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.

  1. /*
  2.  * C++ program to Solve Tower of Hanoi Problem using Binary Value
  3.  */
  4. #include<stdio.h> 
  5. #include<conio.h>
  6. #include<iostream>
  7. using namespace std;
  8. int main()
  9. {
  10.     int n, x;
  11.     cout<<"\nEnter the No. of Disks: ";
  12.     cin>>n;
  13.     for (x = 1; x < (1 << n); x++)
  14.     {
  15.         printf("\nMove from Peg %i to Peg %i", (x&x-1)%3+1, ((x|x-1)+1)%3+1);
  16.     }
  17.     cout<<"\n";
  18.     getch();
  19. }

advertisement
Output
Enter the No. of Disks: 4
 
Move from Peg 1 to Peg 3
Move from Peg 1 to Peg 2
Move from Peg 3 to Peg 2
Move from Peg 1 to Peg 3
Move from Peg 2 to Peg 1
Move from Peg 2 to Peg 3
Move from Peg 1 to Peg 3
Move from Peg 1 to Peg 2
Move from Peg 3 to Peg 2
Move from Peg 3 to Peg 1
Move from Peg 2 to Peg 1
Move from Peg 3 to Peg 2
Move from Peg 1 to Peg 3
Move from Peg 1 to Peg 2
Move from Peg 3 to Peg 2

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.