Computer Programming C Laboratory: Functions C Programs

C Program to demonstrate tower of Hanoi

tower of Hanoi - C Programming

C Program to demonstrate tower of Hanoi.

/* C Program using tower of Hanoi */

#include <stdio.h>

main()

{

void hanoi (int, char, char, char); /* Local definition */

/* Statements */

int n;

printf ("How many disk... \n");

scanf("%d", &n);

hanoi (n, 'L', 'R', 'C');

} /* main */

void hanoi (int n, char from, char to, char t)

{

          if (n>0)

          {

                    hanoi (n‒1, from, temp, to);

                    printf ("Move disk %d from %c to %c\n", n, from, to);

                    hanoi (n‒1, temp, to, from);

          } /* if */

} /* hanoi */

OUTPUT

How many disk….. 3

Move disk 1 from L to R

Move disk 2 from L to C

Move disk 1 from R to C

Move disk 3 from L to R

Move disk 1 from C to L

Move disk 2 from C to R

Move disk 1 from L to R

EXPLANATION: In the above program the number of disk n is read and call the subprogram hanoi() from the main function. The function hanoi() checks the condition if (n>0) condition is true then the block of statements are executed and print the poles and sides of the disk. In the program the function hanoi() is referred as a recursion. Where L, R, C are the labels of the poles, i.e., left (L), center (C) and Right (R) and L(From), R(To) and C(t) are the their sources and destination.

Computer Programming C Laboratory: Functions C Programs : Tag: C Programming : - C Program to demonstrate tower of Hanoi


Computer Programming C Laboratory: Functions C Programs



Under Subject



Related Subjects