简体   繁体   中英

Why does the bubble sort program show the garbage value when using "break" in for loop?

This code will take the elements of the array from the user and then sort it. The user input limit is 20. I have an issue with a specific line which is if (a[i]==0)break; if I use break here the result shows garbage values. Otherwise, it works fine but I want the user to be able to run the program with 20 or fewer numbers. I meant they can simply enter 0 whenever they feel they are done, and so the loop breaks. I am giving the code below. Please try to give simple solutions and don't be toxic and snooty. Thank you.

//Sorting with user input array elements
void print(float a[], int n)
{
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
}

void sort(float a[], int n)
{
    for (int i = 1; i < n; i++) {

        for (int j = 0; j < n - i; j++) {
            if (a[j] > a[j + 1]) {
                swap(a[j], a[j + 1]);
            }
        }
    }
}

int main()
{
    float a[20];
    int size;
    court << "Enter Floats and terminate with 0 (Highest limit is 20)" << endl;
    for (int i = 0; i <= 20; i++) {
        cout << "a[" << i << "] : ";
        cin >> a[i];
        if (a[i] == 0)
            break;
    }
    size = sizeof(a) / sizeof(int);

    cout << "\nGiven Values   :: ";
    print(a, size);
    cout << endl;
    sort(a, size);
    cout << "Sorted Result    :: ";
    print(a, size);
}

The array has size 20. The user sets values until 0 is entered. That means that the other elements are uninitialized. These are the garbage values. You can fix it by saving the number of entered elements.

//Sorting with user input array elements
void print(float a[], int n)
{
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
}

void sort(float a[], int n)
{
    for (int i = 1; i < n; i++) {

        for (int j = 0; j < n - i; j++) {
            if (a[j] > a[j + 1]) {
                swap(a[j], a[j + 1]);
            }
        }
    }
}

int main()
{
    float a[20];
    int size{0};
    court << "Enter Floats and terminate with 0 (Highest limit is 20)" << endl;
    for (int i = 0; i < 20; i++) {
        cout << "a[" << i << "] : ";
        cin >> a[i];
        if (a[i] == 0)
            break;
        ++size;
    }

    cout << "\nGiven Values   :: ";
    print(a, size);
    cout << endl;
    sort(a, size);
    cout << "Sorted Result    :: ";
    print(a, size);
}

There is also a problem in the for loop. The array has size 20 but the for loop starts with 0 and iterates until 20 inclusive. That are 21 iterations. I fixed it in my answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM