[Solved] rand() and sorting do not work as expected in C from thenewboston tutorial 41 [closed]


It’s just a simple mistake where you must use the variable i instead of a constant. If I change your code and use the variable instead of the constant, then the code works.

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

int main()
{
    int i, temp, swapped;
    int howMany = 10;
    int goals[howMany];

    for (i=0; i<howMany; i++) {
        goals[i] = ( rand()%25 ) + 1;
    }

    printf("Original List\n");

    for (i=0; i<howMany; i++) {
        printf("%d \n", goals[i]);
    }

    while(1) {
        swapped = 0;

        for (i=0; i<howMany-1; i++) {
            if (goals[i]>goals[i+1]) {
                temp = goals[i];
                goals[i] = goals[i+1];
                goals[i+1] = temp;
                swapped = 1;
            }
        }

        if (swapped==0) {
            break;
        }
    }

    printf("\nSorted List\n");

    for (i=0; i<howMany; i++) {
        printf("%d \n", goals[i]);
    }

    return 0;
}

Output

$ ./a.out 
Original List
9 
12 
3 
16 
19 
11 
12 
18 
25 
22 

Sorted List
3 
9 
11 
12 
12 
16 
18 
19 
22 
25 

If you don’t know this, you should learn about loops and how a loop index works.

solved rand() and sorting do not work as expected in C from thenewboston tutorial 41 [closed]