Help with Sorting Array Code

Hello wonderful people, can someone please help me with my code? I am suppose to have the user enter the number of elements in an array and then have the user enter that amount of elements (I have successfully done this part). After that the program is suppose to repeat the numbers the user entered and then sort them from lowest to highest and display them (one number per line of input, repeating, and sorted; also I used Bubble Sort). This is the part I am struggling with, I have written the code but it only does the first part of the code and then only repeats the first number of the elements and then ends. Can someone please tell me what is wrong with my code and how to improve it?

ps: The commented lines are the directions for the code used below.

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
40
41
42
43
44
45
46
47
48
  #include <iostream>
using namespace std;

int main()
{
    int num;
    cout << "Enter the number of elements(between 2 and 20):";
    cin >>  num ;
    if (num < 2 || num > 20)
    {
        cout << "Invalid input (should be between 2 and 20)" << endl;
        exit(1);
    }
    cout << endl << "Enter " << num << " elements" << endl;

    //Define an array to hold at least 20 "int" elements
    int numbers[20];

    //Accept inputs (num contains the number of inputs to receive)
    cin >> numbers[num];

    //Display the elements of the array (one element per line)
    cout << numbers[num] << " ";

    //Sort the elements, Ascending order, Lowest ---> highest
    int temp;
    for(int i = num-1; i >0; i--)
    {
      for(int j = 0; j < i; j++)
      {
        if(numbers[j] > numbers[j+1])
        {
          temp = numbers[j+1];
          numbers[j+1] = numbers[j];
          numbers[j] = temp;
        }
      }
    }

    //Display the elements of the array (one element per line)
   for (int i =0; i< numbers[i] ; i++)
   {
     cout << numbers[num] << " ";
   }
    cout << endl;
    return 0;
}
1. Read about array indexing from http://www.cplusplus.com/doc/tutorial/arrays/

2. Line 17 is not legal C++. The length of statically allocated array must be known already during compilation. There are three options:
a) Use std::vector rather than plain array. This is the recommended solution
b) Make "big enough" static array. If the user nevertheless gives num bigger than that, handle the error.
c) Use low level dynamic memory allocation.

3. On line 32 you do read element j+1. However, the j can equal to i and i can be num-1. You could try to read (and write) element numbers[num]. The first point here should have explained why that is undefined behaviour.
Thank you very much for your help!
Topic archived. No new replies allowed.