Search⌘ K
AI Features

Solution Review: Recursive Towers of Hanoi

Understand how to solve the Towers of Hanoi problem recursively in C. Learn to use recursion effectively by managing disk moves between pegs, and how base cases and recursive calls work together to solve the problem for any number of disks.

We'll cover the following...

Solution

See the code given below!

C
#include <stdio.h>
void move ( int, char, char, char ) ;
int main( )
{
int n = 3 ;
move ( n, 'A', 'B', 'C' ) ;
return 0 ;
}
void move ( int n, char sp, char ap, char ep )
{
if ( n == 1 )
printf ( "Move from %c to %c\n", sp, ep ) ;
else
{
move ( n - 1, sp, ep, ap ) ;
move ( 1, sp,' ', ep ) ;
move ( n - 1, ap, sp, ep ) ;
}
}

Explanation

The code given above shows the prototype of the move( ) and the first call to ...