Page 177 - DCAP407_DATA_STRUCTURE
P. 177
Data Structure
Hanoi (n, ‘A’, ‘B’, ‘C’);
}
/* Hanoi function definition holds four arguments namely n, source,
dest and spare which are of integer and character data types respectively
*/
void Hanoi (int n, char source, char dest, char spare)
{
/* Check whether n value is equal to 1 */
if (n == 1)
{
/* Prints the values of source and dest */
printf (“\n Transfer disc 1 from needle %c to needle %c”, source,
dest);
}
/* Otherwise */
else
{
/* Hanoi function is invoked within itself with n-1, source, spare and
dest variables*/
Hanoi (n-1, source, spare, dest);
/* Print the values of variables n, source and dest */
printf (“\n Transfer disk %d from needle %c to needle %c”, n,
source, dest);
/* Hanoi function is invoked within itself with n-1, spare, dest and
source variables*/
Hanoi (n-1, spare, dest, source);
}
}
Output:
Input the number of discs: 3
Transfer disk 1 from needle A to needle C
Transfer disk 2 from needle A to needle B
Transfer disk 1 from needle C to needle B
Transfer disk 3 from needle A to needle C
Transfer disk 1 from needle B to needle A
Transfer disk 2 from needle B to needle C
Transfer disk 1 from needle A to needle C
In this example:
1. First, the conio.h header file that creates text user interfaces are
included using the include keyword.
2. Then, the stdio.h header file is included using the include
keyword.
3. Then, Hanoi function is defined globally which holds four
arguments and does not return any value.
4. Then, the main () program is defined.
5. In main ():
(a) First, an integer variable n is initialized.
(b) Then, the number of discs is accepted and stored in n.
(c) Finally, the Hanoi function is invoked.
170 LOVELY PROFESSIONAL UNIVERSITY