What is Tower of Hanoi ?

Tower of Hanoi consists of three pegs or towers with n disks placed one over the other.

The objective of the puzzle or Problem is to move the stack to another peg following these simple rules.

  1. Only one disk can be moved at a time.
  2. No disk can be placed on top of the smaller disk.

Write a Program to solve Tower of Hanoi Problem.

Program

#include <iostream.h>
#include <conio.h>
//Function
void tower(int disc,char left,char centre,char right){
	if(disc==1){
		cout<<"\nMove Disc 1 from "<<left<<" to "<<right;
		return;
	}else{
		tower(disc-1,left,right,centre);
		cout<<"\nMove Disc "<<disc<<" from "<<left<<" to "<<right;
		tower(disc-1,centre,left,right);
	}
}
void main(){
//Clear Screen
	  clrscr();
//Variables
	  int n;
	  cout<<"\n----Tower of Hanoi----";
	  cout<<"\nEnter number of discs : ";
	  cin>>n;
	  //	Disc,left,Centre,Right
	  tower(n,'A','B','C');
	  getch();
}

Program Output:

(Visited 3,003 times, 1 visits today)
Share with Friends :
Written by:

Leave a Reply

Your email address will not be published. Required fields are marked *