# Tower of Hanoi--Algorithm Error

I’m having trouble understanding the algorithm for the Tower of Hanoi that is posted on the Blog. The issue is that it’s not always moving the disks from the source peg to the destination peg correctly. I’ve identified the code that seems to be causing the problem, but I’m not sure how to fix it.

Code:

``````// Move n disks from source peg to dest peg using a temp peg
void moveDisk(int n, char source, char dest, char temp)
{
// If only one disk then move it.
if (n == 1)
{
printf("Move disk 1 from peg %c to peg %c\n", source, dest);
return;
}

// Move n-1 disks from source peg to temp peg using dest peg
moveDisk(n-1, source, temp, dest);

// Move nth disk from source peg to dest peg
printf("Move disk %d from peg %c to peg %c\n", n, source,
dest);

// Move n-1 disks from temp peg to dest peg using source peg
moveDisk(n-1, temp, dest, source);
}
``````

Any help would really be appreciated. Thanks!

After reviewing the code, it seems like the algorithm in your is correct for solving the Tower of Hanoi puzzle. The code uses a recursive approach to solve the problem and it follows all the steps of Tower of Hanoi puzzle.
The ‘moveDisk’ function implements these steps correctly, and the code should work as expected to solve the Tower of Hanoi puzzle.
If you are observing any issues or errors, they are likely not related to the algorithm or logic in the provided code. The issue might be with how you are calling the function, providing the input values (n, source, dest, temp), or handling the output. Please double-check your function calls and inputs to ensure they are set up correctly.

Thank You

Hi @singhalishaas60
There is a minor formatting issue in the printf statements. The format specifier for the disk number should be %d, not %c. Here’s the corrected code with the formatting fixed:

// Move n disks from source peg to dest peg using a temp peg
void moveDisk(int n, char source, char dest, char temp)
{
// If only one disk then move it.
if (n == 1)
{
printf(“Move disk 1 from peg %c to peg %c\n”, source, dest);
return;
}

``````// Move n-1 disks from source peg to temp peg using dest peg
moveDisk(n-1, source, temp, dest);

// Move nth disk from source peg to dest peg
printf("Move disk %d from peg %c to peg %c\n", n, source, dest);

// Move n-1 disks from temp peg to dest peg using source peg
moveDisk(n-1, temp, dest, source);
``````

}

int main() {
int numDisks = 3; // Number of disks
char source = ‘A’; // Source peg
char dest = ‘C’; // Destination peg
char temp = ‘B’; // Temporary peg

``````moveDisk(numDisks, source, dest, temp);

return 0;
``````

}

With this corrected code, it should work as expected and correctly print the steps to solve the Tower of Hanoi problem for the given number of disks.