Explain recursion. Also write a C program
for Tower of Hanoi problem with
a example of 4 disks
The C language allows programmer to write
functions that calls themselves and this is called Recursion.
#include<stdio.h>
#include<conio.h>
void
TOH(int,char,char,char);
void
main()
{
int
n;
clrscr();
printf(“Enter
the number of disk: “);
scanf(“%d”,&n);
printf(“Tower
of hannoi problem for %d disk: \n”,n);
TOH(‘n’,’A’,’B’,’C’);
getch();
}
void
TOH(int n, char A, char B, char C)
{
if(n<=0)
printf(“\n
Wrong input \n”);
else
if(n==1)
printf(“\n
Move disk from peg %c to peg %c”,A,C);
else
{
TOH(n-1,A,C,B);
TOH(1,A,B,C);
TOH(n-1,B,A,C);
}
}
No comments:
Post a Comment