0

(C++) My program should be getting the user to input numbers which will determine the size of the array and as well as what its elements are. I then need to sort out the elements in an ascending order. My problem is whenever I run my program and it displays the sorted numbers; instead it displays the address(if I'm correct).

    #include <iostream>
    using namespace std;


int main()
{

   int size;
   int i,x,tempVar;
   cout << "Enter how many students took the test: ";
   cin >> size;
   int *myArray = new int [size];

for  ( i = 0; i < size; i++)
{
    cout << "Enter a score:  ";
    cin >> myArray[size];
}

for ( i = 0; i < size; i++)
{
    for ( x = 0; x < size; x++)
    {
        if (myArray[i] < myArray[x])
        {
            tempVar = myArray[i];
            myArray[i] = myArray[x];
            myArray[x] = tempVar;
        }
    }
}

cout << "The scores have been sorted out in an ascending order\n";
for (i = 0; i < size; i++)
{
    cout << *(myArray + i) << endl;
}

delete [] myArray;
}
user3164168
  • 11
  • 1
  • 2
  • Give us an example of what's being printed and what you expected. – David G Jan 27 '14 at 02:50
  • Your reading is wrong: `cin >> myArray[size];` should be `cin >> myArray[i];` – rendon Jan 27 '14 at 02:50
  • Your sort loop is not very well thought out. The first thing it's going to do is compare `myArray[i=0]` with `myArray[x=0]`, and overall it's going to require size*size operations - it's going to be slow. – kfsone Jan 27 '14 at 03:39
  • Also, you can simplify your code by writing `if (myArray[i] < myArray[x]) std::swap(myArray[i], myArray[x]);` – kfsone Jan 27 '14 at 03:40

1 Answers1

1

It's not showing addresses; it's probably showing the garbage values since you have:

cin >> myArray[size];

instead of

cin >> myArray[i];
younis
  • 357
  • 1
  • 7