Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I was trying to sort elements of an array in C++, but the program doesn't work for 4 elements. I am a beginner, could you help me out with this?

Program to sort elements in an array – I ran it using an online IDE, but the code won’t work for 4 elements. I tried different values, but it simply won’t give the output.

int main()
{
    int el = 0, num = 0;
    cout << "Enter the number of elements in an array:" << endl;
    cin >> el;
    int a[el];
    cout << "ENTER ELEMENTS:" << endl;
    for (int i = 0; i < el; i++)
    cin >> a[i];
    for (int j = 0; j < el; j++)
    {
        for (int i = 0; i < el; i++)
        {
            if (a[i] > a[i+1])
            {
                num = a[i + 1];
                a[i + 1] = a[i];
                a[i] = num;
            }  
        }
    }
    for (int i = 0; i < el; i++)
    {
        cout << a[i];
        cout << endl;
    }
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As someone has already mentioned, int a[el] is not standard C++ unless el is a constant value, known at compile time. You should specify the maximum number of elements by a constant, or you can check std::vector if you want to provide the size of the array at runtime.

As for the question, the bug is here:

for (int j = 0; j < el; j++) {
    for (int i = 0; i < el; i++) {
        if (a[i] > a[i + 1]) {
            // ... the rest of the code
        }
    }
}

When i = el - 1, the expression a[i + 1] tries to access unitialised memory, which is undefined behaviour. Change this second for to this

for (int i = 1; i < el; i++) {
    if (a[i - 1] > a[i]) {
       // the rest of the code
    }
}

and everything should be fine (just keep in mind to change the code using i as well!).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading