Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

give n discks stacked on the leftmost peg in order of size with the largest the

ID: 3545693 • Letter: G

Question

give n discks stacked on the leftmost peg in order of size with the largest the bottom anda disk is always smaller then the disc below.

so move all n discs from left most peg a to right most pegc. only one disc may moved at a time disc can not be placed on the top of a smaller disc . only three pegs: ABC


so i have to display every move and indicate the position of each disc:

ex: beginning poition of three discs:(A,A,A)

disca is smaller than disc 2 and disc 2 is smaller than disc 3.

move dis1 from pegA to peg C(C,A,A).....etc

do the same for n=4 and 5


please check my cods actually i dont have a idea to indicate all postions .


#include<iostream>

#include<string>


using namespace std;


void moveDiscs(int, string,string,string);


int main()

{

int num;

cout<<"Enter the number of Disks: ";;

cin>>num;


moveDiscs(num,"A","B","C");


return 0;

}


void moveDiscs(int num, string from, string to, string temp)


{

if( num==1)

{

cout<<"Move disc 1 from Peg"<<from<<"to"<<to;

return ;

}

moveDiscs(num-1,temp,to,from);

cout<<endl<<"move"<<num<<"frompeg"<<from<<"to" <<to;

moveDiscs(num-1,temp,to,from);

}

Explanation / Answer

#include "iostream"

using namespace std;

char a[1000];

int n,tot;


void towers(int,char,char,char);


void towers(int n,char frompeg,char topeg,char auxpeg)

{

int i;

/* If only 1 disk, make the move and return */

if(n==1)

{

//printf(" Move disk 1 from peg %c to peg %c",frompeg,topeg);

a[1]=topeg;

cout<<"(";

for(i=1;i<=tot;i++)

cout<<a[i]<<",";

cout<<") ";

return;

}

/* Move top n-1 disks from A to B, using C as auxiliary */

towers(n-1,frompeg,auxpeg,topeg);

/* Move remaining disks from A to C */

a[n]=topeg;

cout<<"(";

for(i=1;i<=tot;i++)

cout<<a[i]<<",";

cout<<") ";

//printf(" Move disk %d from peg %c to peg %c",n,frompeg,topeg);

/* Move n-1 disks from B to C using A as auxiliary */

towers(n-1,auxpeg,topeg,frompeg);

}

main()

{

int i;

cout<<"Enter the number of disks : ";

cin>>n;

tot=n;

cout<<"The Tower of Hanoi involves the moves : ";

cout<<"(";

for(i=1;i<=tot;i++)

{

a[i]='A';

cout<<a[i]<<",";

}

cout<<") ";

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

return 0;

}