input and sort array

I wanted to make a program where i input the number of elements in the array, input the elements value, and the program outputs all the elements in crescent order. I have no error but sometimes it outputs an element i didn't input in the right order.

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
#include <iostream>
#include <cstdlib>
using namespace std;

int main (){
    int num;
    int holder;
    cin >> num;
    int fine=num;
    int myarray[num];
    for(int i=0;i<num;i++){
        cin >> myarray[i];
    }
    cout << "\n\n";
    for(int i=0;i<num;i++){
        for(int i=0;i<fine;i++){
            if(myarray[i]>myarray[i+1]){
                holder=myarray[i+1];
                myarray[i+1]=myarray[i];
                myarray[i]=holder;
            }
        }
        fine--;
    }
    for(int i=0;i<num;i++){
        cout << myarray[i] << endl;
    }
}



Line 10 is an error. The size of array must be known during compilation. (Your compiler may support such non-standard feature.)

Make a "big enough" array and test during runtime that 'num' is not too big.

You have 'i' on line 15 loop, but you have (different) 'i' on line 16 loop.

You refer to element i+1 on lines 17-19. Thus, when fine==num and i==fine-1, you do refer to element 'num'. That is an out of range error with undefined consequences.
A simpler one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <array>
#include <algorithm>

using namespace std;

int main(){
array<int,6> arr{5,3,99,52,47,803};

sort(arr.begin(),arr.end());

for(auto x:arr){
cout<<x<<", ";
}

return 0;
}
Topic archived. No new replies allowed.