Wednesday, 22 November 2017

C++ program to Solve Tower of Hanoi Problem using Binary Value


Code:

#include    stdio.h
#include    conio.h
#include    iostream
using namespace std;
int main()
{
    int n, x;
    cout<<"\nEnter the No. of Disks: ";
    cin>>n;
    for (x = 1; x < (1 << n); x++)
    {
        printf("\nMove from Peg %i to Peg %i", (x&x-1)%3+1, ((x|x-1)+1)%3+1);
    }
    cout<<"\n";
    getch();
}


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



More C++ Programs:














100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...