Sorting int's

Mar 5, 2012 at 6:23pm
I am trying to write a code that will sort three integers from lowest to highest but my code isn't producing the desired results. The code only cout's the number in the middle three times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int numb[3];
    int i, j;

    for(i=0;i<=2;i++)
    {
        cout << "Please enter a number: ";
        cin >> numb[i];
    }

    for(i=0;i<=2;i++)
    {
        for(j=i+1;j<=3;j++)
        {
          int temp;

          if(numb[i] > numb[j])
          {
              temp = numb[i];
              numb[i] = numb[j];
              numb[j] = temp;
          }
        }
    }

    for(i=0;i<=2;i++)
    {
        cout << endl << numb[1] << endl;
        cout << endl;
    }

    system("pause");
}
Mar 5, 2012 at 6:37pm
You need to watch the loop index here (you're going out of bounds):

for(j=i+1;j<=3;j++)

The code only cout's the number in the middle three times.

That's exactly what you're doing:

1
2
3
4
5
for(i=0;i<=2;i++)
{
   cout << endl << numb[1] << endl; //you're printing numb[1], not numb[i]
   cout << endl;
}
Last edited on Mar 5, 2012 at 6:38pm
Mar 5, 2012 at 6:46pm
I changed the [1] to and i and it seems to be working better.

I dont understand going out of bounds?

Now the program outputs the numbers in the correct order, but for some reason the first number defaults to zero for some some reason example 0, 14, 25 even tho I inputted 1, 14, 25.


Mar 5, 2012 at 6:54pm
I dont understand going out of bounds?

The numb array has 3 elements, thus the maximum possible index is 2. In this for loop,

for(j=i+1;j<=3;j++)

j is going up to 3. When j reaches 3 and the array is accessed using j, this is undefined behaviour. Make sure that j doesn't exceed 2, here.
Last edited on Mar 5, 2012 at 6:55pm
Mar 5, 2012 at 7:05pm
Changing it to a 2 did the trick, now it works great.
Topic archived. No new replies allowed.