Amin Husni
Amin Husni

Reputation: 25

C program keeps crashing

My program keeps crashing. The codes seems legit and correct. Wonder what's the problem.

#include <stdio.h>

void queue(int length,int turns){
    int permutations,totalTurns;
    turns++;
    if (length>0){
        queue(length-1,turns);
        if (length>1){
            queue(length-2,turns);
        }
    } 
    else{
        permutations++;
        totalTurns+=turns;
    }
}

int main() 
{
    while(true){
        int length;
        float average;
        int permutations=0;
        int totalTurns=0;

        printf("Queue length: ");
        scanf("%d", &length);
        queue(length,-1);
        average=totalTurns/permutations;
        printf("The average turns are %f", average);
    }
}

Upvotes: 0

Views: 245

Answers (2)

Templar
Templar

Reputation: 1871

You should declare permutations as a global variable, i.e. outside main function as well as totalTurns because as others mentioned it's always 0 because even thought you declare it in function queue it's being forgotten outside it.

#include <stdio.h>

static int permutations=0;
static int totalTurns=0;


void queue(int length,int turns){
    turns++;
    if (length>0){
        queue(length-1,turns);
        if (length>1){
            queue(length-2,turns);
        }
    } 
    else{
        permutations++;
        totalTurns+=turns;
    }
}

int main() 
{
    while(true){
        int length;
        float average;
        int totalTurns=0;

        printf("Queue length: ");
        scanf("%d", &length);
        queue(length,-1);
        average=totalTurns/permutations;
        printf("The average turns are %f", average);
    }
}

Upvotes: 2

Graham Borland
Graham Borland

Reputation: 60681

    int permutations=0;

    average=totalTurns/permutations;

You're dividing by zero.

Note that the permutations variable you've declared in main() is different from the one in queue().

You should probably return the permutations value from queue(), like this:

int queue(int length,int turns){
    int permutations = 0;
    ...
    return permutations;
}

int main(void) {
    ...
    int permutations = queue(length,-1);
}

Upvotes: 7

Related Questions