lundi 24 juin 2019

Program ends before I type A or D for bubble sorting

I am practising bubble sort, and try to arrange a sequence of numbers in array to be in ascending order or descending order. The questions asked to build a program that uses a single-dimension array to store 12 numbers input by user. After inputting the numbers, the user should see a menu with two options to sort and print the 12 numbers in ascending or descending order.

#define SIZE 12

//Bubble sort
//Loop to control number of passes
void Bubblesort(int a[SIZE]){
    for (unsigned int pass = 1; pass < SIZE; ++pass) {
        // loop to control number of comparisons per pass
        for (size_t i = 0; i < SIZE - 1; ++i) {
            // Compare adjacent elements and swap them if first element is greater than second element
            if (a[i] > a[i + 1]) {
                int hold = a[i];
                a[i] = a[i + 1];
                a[i + 1] = hold;
            }
        }
    }
}
// function main begins program execution
int main(){
    int a[SIZE];    //Define array
    char enter; //Define character input by user
    printf("Enter the elements of array\n");

    for(size_t i=0;i<SIZE;i++){
        scanf("%d", &a[i]);
    }

    puts("Data items in original order");
   // output original array
    for (size_t i = 0; i < SIZE; ++i){
        printf("%4d", a[i]);
        }
    void Bubblesort(int a[SIZE]);
    puts("\nDo you want to print out the elements in ascending order (press A) or in descending order (press D)?");
    scanf("%c", &enter);
    if(enter=='A'){
    puts("\nData items in ascending order");
    // output sorted array
    for (size_t i = 0; i < SIZE; ++i) {
         printf("%4d", a[i]);
        }
    } else if (enter=='D') {
    puts("\nData items in descending order");
    // output sorted array
    for (size_t i = 0; i < SIZE; ++i) {
        printf("%4d", a[SIZE-i-1]);
        }
    puts("");
    }
    else return 0;
}

This is the result shown in XCode:

Enter the elements of array
1 2 3 5 4 7 8 6 9 11 12 10
Data items in original order
   1   2   3   5   4   7   8   6   9  11  12  10
Do you want to print out the elements in ascending order (press A) or in descending order (press D)?
Program ended with exit code: 0

I expected I will type A or D when it asks 'Do you want to print out the elements in ascending order (press A) or in descending order (press D)', but it executes when the sentence is printed.

Aucun commentaire:

Enregistrer un commentaire