hey can anyone explain this code to me, i am trying to understand it for days now but i still cant figue it out its the code of "the towers of hanoi"........it goes like this...


#include <stdio.h>

void hanoi(int n,char from,char aux,char to) {
if (n==0){
return;}
hanoi(n-1,from,to,aux);
printf("\nMove disk %d from %c to %c",n,from,to);
hanoi(n-1,aux,from,to);
}

void main(void) {
int exit;
hanoi(3,'a','b','c');
scanf("\n%d",&exit);
}

It uses recursion -- if you don't know what recursion is then you won't understand how the program works. Other than that, it is a poorly written program.

i understand recursion, i know that recursion is a function that calls itself. is it possible to explain each line of the code until the program exit. i would appreciate it..... its been days since i have been trying to figure it out but....i am still going no where with it....

when the program run the output of "N" is 1,2,1,3, 1,2,1 after the statement is print 7 times. i need to know how is that possible....

>>i need to know how is that possible....
Get out a pencil & paper then step through the program youself and you will see how it works. The first time hanoi is called from main() the value of N is 3. Since N is not 0 the test on line 5 will fail and line 9 is executed. It subtracts 1 form N and calls hanoi again with the value of 4. This repeats itself until 0 is reached at which time line 7, the return, is executed. Then line 10 is executed with N = 1. Now you can trace through that program with pencil & paper writing down the values of N at each step of the program.

#include<stdio.h>

void hanoi(int n,char from,char aux,char to) 
{
    if (n==0)
    {
        return;
    }
    hanoi(n-1,from,to,aux);
    printf("\nMove disk %d from %c to %c",n,from,to);
    hanoi(n-1,aux,from,to);
}

int main(void) {
   hanoi(3,'a','b','c');
   getchar();
   return 0;
}

after the 1 is printed in the print statement and the function is again called below the print statement the program is now going to ignore the top structure call right?
And why is the value now 2. is it safe to say it increment?

can anyone tell why and how the recursion return to a previous value of the variable N???

As a simplistic explanation, each time you call the recursive function, a new copy of the function is created, including new variables. The values of the variables in the previous copy are not destroyed, so when the new function returns, the values are as they were before the call was made.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.