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;
}
4
  • Give us an example of what's being printed and what you expected. Commented Jan 27, 2014 at 2:50
  • Your reading is wrong: cin >> myArray[size]; should be cin >> myArray[i]; Commented Jan 27, 2014 at 2: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. Commented Jan 27, 2014 at 3:39
  • Also, you can simplify your code by writing if (myArray[i] < myArray[x]) std::swap(myArray[i], myArray[x]); Commented Jan 27, 2014 at 3:40

1 Answer 1

1

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

cin >> myArray[size];

instead of

cin >> myArray[i];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.