Home > Net >  I need help for bubble sort in c
I need help for bubble sort in c

Time:09-30

How can I display the input user of this code. I am using bubble sort but I cannot display the input.

Here's my code:

    #include <stdio.h>

    int main(void) {
    int array[100];

    int count;

    for(int i = 0; i < 100; i  ) {
        printf("Enter number %d: ", i   1);
        scanf("%d", &array[i]);
        if(array[i] == 0) break;
    }

    int size = sizeof(array) / sizeof(array[0]);
    for(int i = 0; i < size - 1;   i) {
        int swapped = 0;
        for(int ctr = 0; ctr < size - i - 1;   ctr) {
            if(array[ctr] > array[ctr   1]) {
                int temp = array[ctr];
                array[ctr] = array[ctr   1];
                array[ctr   1] = temp;

                swapped = 1;
            }
        }
        if(swapped == 0) {
            break;
        }
    }
    
    printf("[");
    for(int i = 0; i < size; i  ) {
        if(i == size - 1) {
            printf("%d", array[i]);
        }
        else {
            printf("%d, ", array[i]);
        }
    }
    printf("]");
        
    return 0;
    }

Here's the output:

Enter·number·1:·1
Enter·number·2:·2
Enter·number·3:·3
Enter·number·4:·4
Enter·number·5:·5
Enter·number·6:·0
[1,·2,·3,·4,·5]

I cannot display the 1 2 3 4 5.... How can I display?

CodePudding user response:

The user can enter i values in the array due to the break statement within the for loop

for(int i = 0; i < 100; i  ) {
    printf("Enter number %d: ", i   1);
    scanf("%d", &array[i]);
    if(array[i] == 0) break;
}

So you need to keep this value and use it the following for loops because it can differ from the value of the expression sizeof(array) / sizeof(array[0])

CodePudding user response:

The calculation of the size doesn't work like you did it. sizeof(array) will give you the total amount of of bytes of the array (of all 100 spaces). So your size will allway be 100.

Instead of calculating the size it's easyer to count the inputs like this:

int size=0;

for(int i = 0; i < 100; i  ) {
    printf("Enter number %d: ", i   1);
    scanf("%d", &array[i]);
    if(array[i] == 0) break;
    size  ;
}
  • Related