Borislav Nikolaev
Borislav Nikolaev

Reputation: 69

Arrays messed up C++

const int N = 5;

int person[] = {2, 3, 12, 5, 19};
int big = 0;
int small = 100;
int i;

for (i = 0; i <= N; i++)
{
    cout << "Person[" << i << "] ate: " << person[i] << endl;
    //cin >> person[i];

    for (int j = i+1; j <= N; j++)
    {
        if (person[i] < person[j])
        {
            int tmp = person[i];
            person[i] = person[j];
            person[j] = tmp;
        }
    }
            if (person[i]>big)
        big=person[i];
    if (person[i]<small)
        small=person[i];
}
    cout << "Person[" << i << "] ate the most pancakes: " << big << endl;
    cout << "Person[" << i << "] ate the least pancakes: " << small << endl;

    cout << "Sorted:" << endl;
    for (i = 0; i < N; i++)
    {
        cout << "Person[" << i << "]: " << person[i] << endl;
    }




    system("pause");

output

Where I messed up those arrays it keeps showing me 2 but the bubble sorting works. And the other question is how to get the array index from the smallest value and the array index from the highest value?

Upvotes: 0

Views: 253

Answers (2)

mazhar islam
mazhar islam

Reputation: 5629

In C++ arrays are ZERO 0 indexed. So you should change your for loops like this:

for (i = 0; i < N; i++)
             ^^^
{
    // some code...
    for (int j = i+1; j < N; j++)
                       ^^^
    {
        // some code...

Because:

index    -> 0  1  2   3  4 
person[] = {2, 3, 12, 5, 19};

In your code the value of i and j will increment up to N which is 5. That means you are trying to access the array named person's 5th index which will create array index out of bound error.

Upvotes: 1

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

Array indexing starts from zero so if there are N elements, last element will be at N-1 index.Accessing element at index N is going out of bounds.

for (i = 0; i <= N; i++)//should run till `N-1` 
              ^^^

for (int j = i+1; j <= N; j++)//should run till `N-1`
                     ^^^

If you want index of the highest and the lowest element,since you have sorted the array,the smallest values's index would be 0 and highest value's index will be N-1(opposite in your case because you have sorted the array in decreasing order)

Upvotes: 1

Related Questions