This C++ Program uses recursive function & solves the tower of hanoi. The tower of hanoi is a mathematical puzzle. It consists of threerods, and a number of disks of different sizes which can slideonto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. We have to obtain the same stack on the third rod.

Here is the source code of the C program for solving towers of hanoi.

#include<iostream>

using namespace std;

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

int main()

{

int num;

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

cin>>num;

cout<<"The sequence of moves involved in the Tower of Hanoi are :\n";

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

return 0;

}

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

{

if (num == 1)

{

cout<<"\n Move disk 1 from peg"<<frompeg<<"to peg "<< topeg;

return;

}

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

cout<<"\n Move disk "<<num<<"from peg"<<frompeg<<" to peg "<<topeg;

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

}

Here is the source code of the C program for solving towers of hanoi.

__Code:__#include<iostream>

using namespace std;

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

int main()

{

int num;

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

cin>>num;

cout<<"The sequence of moves involved in the Tower of Hanoi are :\n";

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

return 0;

}

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

{

if (num == 1)

{

cout<<"\n Move disk 1 from peg"<<frompeg<<"to peg "<< topeg;

return;

}

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

cout<<"\n Move disk "<<num<<"from peg"<<frompeg<<" to peg "<<topeg;

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

}

__Output:__

## 0 Questions:

Post a comment