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.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>>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;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
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.
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953