0

Im still a relatively new programmer trying to grasp recursion. I have looked over various online tutorials on how they work and they make it seem easy to understand. But when I stumbled upon this question I have troubles attempting to follow how the program runs.

#include <stdlib.h>
#include <stdio.h>

void hanoi(int n);

int main (int argc, char *argv[]) {
    hanoi(2);
}


void hanoi( int n ) {
    printf("\n\n--------!n-------: %d\n\n", n);
    if ( n > 0 ) {
        hanoi ( n - 1 );
        printf("\n\n--------#n---------: %d\n\n", n);
        hanoi ( n - 1 );
        printf("\n\n-------$n---------: %d\n\n", n);
    }
}

output

!n: 2

!n: 1

!n: 0

#n: 1

!n: 0

$n: 1

#n: 2

!n: 1

!n: 0

#n: 1

!n: 0

$n: 1

$n: 2

So I was hoping that someone could step through this program and help me understand how recursion really works.

Edit: -Sorry about the photos-

dynaman
  • 31
  • 3

1 Answers1

0

You want to move n blocks from pin 1 to pin 3.

You can do that by:

  1. moving all but the bottom block to pin 2. This requires several moves and is equivalent of solving hanois tower for n-1 blocks, hence the call to hanoi(n-1).

  2. Move the bottom block to pin 3. This is a single move.

  3. Finally move the remaining blocks from pin 2 to pin 3. This requires several moves and is equivalent of solving hanois tower for n-1 blocks, hence the second call to hanoi(n-1).

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82