188 Intermediate C Programming
return f ( dx - 1 , dy ) + f( dx , dy - 1) ;18
Both of these versions do exactly the same thing. The compiler actually creates temporary
variables if local variables are not used.
13.3 The Tower of Hanoi
The listing below shows how to calculate the number of moves required to move n disks
in The Tower of Hanoi problem:
// hanoi1 . c1
// calc ulate the number of moves needed to move n disks2
#in clude < stdio .h >3
#in clude < stdlib .h >4
int f( i n t n)5
{6
/* Base case */7
i f (n == 1)8
{9
return 1;10
}11
/* Recu rsive case */12
return 2 * f (n - 1) + 1;13
}14
int main ( i n t argc , char * argv [])15
{16
int n;17
i f ( argc < 2)18
{19
printf (" need one positive integer . n") ;20
return EXIT _FAILUR E ;21
}22
n = ( in t ) strtol ( argv [1] , NULL , 10) ;23
i f (n <= 0)24
{25
printf (" need one positive integer . n") ;26
return EXIT _FAILUR E ;27
}28
printf (" f(% d) = % d . n" , n , f ( n) );29
return EXIT _SUCCES S ;30
}31
A more interesting program prints the solution—the sequence of disk moves that solves
the problem. To do this, we create a function called move that takes four arguments:
1. The disks to move. The disks are represented by positive integers, where 1 is the
smallest disk and 2 is the second smallest disk, etc.
2. The source pole
3. The destination pole
4. The additional pole
This program follows the procedure in Section 12.3: Move the top n − 1 disks to the
additional pole (i.e., C), then move the n
th
disk from A to B, and then move the top n − 1
disk from C to B. Notice how short and simple the code is.