Search code examples
cfunctionbubble-sort

C programming with functions


I have got some more problems with the code. This program ask the user to specify the nr of throws then it throws 3 dices and add these 3 dices to sum.

Then another function sorts the sum form the smallest to the largest with a bubble sorting algorithm.

the first two functions seems to work but the program does not print out the result of the 3rd sorting function.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 100

//This function ask the user for the amout of throws
int numberofthrows() {
    int throws
    printf("Type in the number of throws");
    scanf("%d", &throws);
    return throws;
}

//This function makes the random throws of 3 dices with regard to the number of throws    

int filler(int thrownr, int dice1[MAX], int dice2[MAX], int dice3[MAX], int    sum[MAX]) {
    int i, nr;
    srand(time(NULL));
    for(i = 0; i <= thrownr; i++) {
        nr = rand()%6;
        dice1[i] = nr + 1;
        nr = rand()%6;
        dice2[i] = nr + 1;
        nr = rand()%6;
        dice3[i] = nr + 1;
        sum[i] = dice1[i] + dice2[i] + dice3[i];
    }

    int j;
    for(j = 0; j <= thrownr; j++) {
        printf("%d ", dice1[j]);
        printf("%d ", dice2[j]);
        printf("%d ", dice3[j]);
        printf("%d\n", sum[j]);
    }
}

//This function sorts the result in form the sum array

int sorter(int thrownr, int sum[MAX], int sortsum[MAX]) {
    int tmp, i, j, k, m;
    for(i = 0; i <= thrownr; i++) {
        sortsum[i] = sum[i];
    }
    for(m = 0; m <= 10; m++) {
        for(j = 0; j <= thrownr; i++) {
            if (sortsum[j] > sortsum[j+1]) {
                tmp = sortsum[j];
                sortsum[j] = sortsum[j+1];
                sortsum[j+1] = tmp;
            }
        }
    }

    for(k = 0; k <= thrownr; k++) {
        printf("%d\n", sortsum[k]);
        printf("%d\n", sum[k]);
    }
}
int main(void) {
    srand(time(NULL));
    int dice1[MAX];
    int dice2[MAX];
    int dice3[MAX];
    int sum[MAX];
    int sortsum[MAX];
    int numberofthrows2;
    numberofthrows2 = numberofthrows();
    filler(numberofthrows2, dice1, dice2, dice3, sum);
    sorter(numberofthrows2, sum, sortsum);
    return 0;
}

Solution

  • The code for sorting is a bit wrong. Change

    for(m = 0; m <= 10; m++)
    

    To

    for(m = 0; m <= thrownr-1; m++)
    

    And

    for(j = 0; j <= thrownr; i++)
    

    To

    for(j = 0; j < thrownr-m-1; i++)
    

    To fix it. Also, call srand once at the start of main. Don't call it more than once in a program or you might get the same "random" numbers everytime you run your program.