Written by Sai Sandeep Thota on January 2, 2013 in C > Programming

Towers of Hanoi Program in C

GET ALERTS:

Get our Latest updates delivered to your mailbox!

We can develop a simple solution for Towers of Hanoi Program in C by using Recursion. Recursion is a function that is called repetitively by itself Recursion can be used directly or indirectly Every recursive function obey base and general rule. The General and Base rule of solving Towers of Hanoi problem has been listed below.

  1. Move (n-1) disk from source to auxiliary (general rule)
  2. Move nth disk from source to destination (base rule)
  3. Move (n-1) disks from auxiliary to destination (general rule)

OLYMPUS DIGITAL CAMERA

Download Source Code

Towers of Hanoi Program

/* C Program to Solve Towers of Hanoi Problem */
#include<stdio.h>
#include<conio.h>

void hanoi(int, char, char, char);

void main()
{
	int disks;
	char source, destination, aux;
	clrscr();
	printf("\nEnter No. of Disks:");
	scanf("%d",&disks);
	printf("\nEnter Source, Destination and Auxillary Disk Names:");
	scanf("%s%s%s",source, destination, aux);
	hanoi(disks,source,destination,aux);
	getch();
}

void hanoi(int n, char s, char d, char a)
{
	if(n>0)
	{
		hanoi(n-1,s,a,d);
		printf("\n%d is moved from %s to %s",n,s,d);
		hanoi(n-1,a,d,s);
	}

}

Output:
Hanoi

There are some limitations for Recursion:

  1. It involve extensive overhead because they use function.
  2. Each time you make a call, you use up some of your memory location and if program ha large number of recursive calls then you may run out of memory.
  3. It is ambiguous to terminate a recursive program in the middle when executing

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: