#include <iostream>
#include <cstdlib>
usingnamespace std;
int main ()
{
int prv_num;
int people [] = {10,1,30,50,20,100,90,15,40,25};
for (int index = 0; index < 10; index++)
{
if (people[index] > people[index + 1])
{
prv_num = people[index + 1];
people[index + 1] = people[index];
people[index] = prv_num;
}
}
for (int index = 0; index < 10; index++)
{
cout<<people[index]<<", ";
}
}
1, 10, 30, 20, 50, 90, 15, 40, 25, 0,
It is suppose to output:
1,10,30,20,50,90,15,40,25,100
Can someone explain to me why this doesn't work. It replaces my highest number with a zero. WHY??? Can it be my compilers fault. I'm using Xcode on mac.
if (people[index] > people[index + 1])
When index is 9, you compare the value at that index (which is the last index) with an element past the end of the array.