It consists of three rods, and a number of disks of different sizes.While transferring disk from one rod other, larger disk can't be at the top of smaller disk.
We have to obtain the same stack on the third rod as in the first rod below:
Here is the source code of the C Program for solving towers of hanoi problem.It was successfully compiled and run in Dev C++.
Source Code:
#include<stdio.h>
void toh(int,char,char,char);
void main()
{
int n;
printf("Enter no. of disks:\n");
scanf("%d",&n);
printf("The steps to solve toh are:\n");
toh(n,'A','B','C');
}
void toh(int n,char frompeg,char auxpeg,char topeg)
{
if(n==1)
{
printf("Move disk 1 from peg %c to peg %c.",frompeg,topeg);
return;
}
toh(n-1,frompeg,topeg,auxpeg);
printf("\nMove disk %d from peg %c to peg %c.\n",n,frompeg,topeg);
toh(n-1,auxpeg,frompeg,topeg);
}
//www.sparajuli.com.np
void toh(int,char,char,char);
void main()
{
int n;
printf("Enter no. of disks:\n");
scanf("%d",&n);
printf("The steps to solve toh are:\n");
toh(n,'A','B','C');
}
void toh(int n,char frompeg,char auxpeg,char topeg)
{
if(n==1)
{
printf("Move disk 1 from peg %c to peg %c.",frompeg,topeg);
return;
}
toh(n-1,frompeg,topeg,auxpeg);
printf("\nMove disk %d from peg %c to peg %c.\n",n,frompeg,topeg);
toh(n-1,auxpeg,frompeg,topeg);
}
//www.sparajuli.com.np