I
I
Iqv2016-01-10 12:58:06
Programming
Iqv, 2016-01-10 12:58:06

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;
}

I enter one number and the program stops working? And how to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aminought, 2016-01-10
@Iqv

Because in scanf you need to pass the address of the variable - &k. Yes, initialize the variable itself.

O
Oleg Tsilyurik, 2016-01-10
@Olej

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 question

Ask a Question

731 491 924 answers to any question