C Program to solve Tower of Hanoi Problem Using Recursion


By on 1:39 PM

This C Program uses recursive function to solve tower of hanoi problem.The tower of hanoi is a mathematical puzzle problem.It is also a great example of recursion.
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:
tower of hanoi
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

About Syed Faizan Ali

Faizan is a 17 year old young guy who is blessed with the art of Blogging,He love to Blog day in and day out,He is a Website Designer and a Certified Graphics Designer.