Answer the question
In order to leave comments, you need to log in
Why does my C program stop running?
Why when I run this program
#include <stdio.h>
void hanoi(int height, int start, int finish)
{
if (height == 1) {
printf("%d %d\n", start, finish);
} else {
int tmp = 6 - start - finish;
hanoi(height - 1, start, tmp);
printf("%d %d\n", start, finish);
hanoi(height - 1, tmp, finish);
}
}
int main()
{
int k;
scanf("%d",k);
hanoi(k,1,2);
return 0;
}
Answer the question
In order to leave comments, you need to log in
Because in scanf you need to pass the address of the variable - &k. Yes, initialize the variable itself.
1. You have already been told about scanf.
(i.e. your program doesn't "stop" as you expected - it just crashes ;-) )
2. You can forward it:
So it's much clearer and more logical than some kind of arithmetic with subtractions.
3. And, if you are already having fun with recursion, then it is more logical to write it like this:
int tmp = start ^ finish;
hanoi( height - 1, start, tmp );
hanoi( 1, start, finish );
hanoi( height - 1, tmp, finish );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question