random order in array

I wanted to have a program that inputs the number of elements in the array, inputs the int variable of the element and outputs the numbers in random order, without repeating the same element twice.
I have no error but sometimes it outputs big numbers i didn't input, thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main (){
    int x;
    cin >> x;
    cout << "\n";
    int y[x];
    srand(time(0));
    for(int i=0;i<x;i++){
        cin >> y[i];
        int random=rand()%x;
        int z=y[i];
        y[i]=y[random];
        y[random]=z;
    }
    cout << "\n\n";
    for(int i=0;i<x;i++){
        cout << y[i] << endl;
    }
}
The way you've created the array on line 10 is only valid if you know the size of the array at compile time. If you only know the size of the array at runtime, fr example after the user enters a value, then you need to dynamically allocate the array using new (and later delete).

http://www.cplusplus.com/doc/tutorial/dynamic/

Or look into using vectors.

http://www.cplusplus.com/reference/vector/vector/


Edit:

On line 16 - y[random] may be an element of the array that hasn't had a value entered yet, so it could have some random garbage value. Which you then store in y[i].

Maybe look into random_shuffle to shuffle the elements in your array after they've been entered.

http://www.cplusplus.com/reference/algorithm/random_shuffle/
Last edited on
Line 10 works with some compilers but it isn't standard C++.

As wildblue says, you're swapping the input number with a random number that might not be initialized. You need to input all the numbers first, then shuffle them, then output the shuffled set of numbers.
alright thanks a lot, i made a third loop only to randomize "i" and it works

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

int main (){
    int x;
    cin >> x;
    cout << "\n";
    int y[x];
    srand(time(0));
    for(int i=0;i<x;i++){ //first loop to input numbers
        cin >> y[i];
    }
    for(int i=0;i<x;i++){ //second loop to randomize position
        int random=rand()%x;
        int z=y[i];
        y[i]=y[random];
        y[random]=z;
    }
    cout << "\n\n";
    for(int i=0;i<x;i++){ // third loop to output numbers
        cout << y[i] << endl;
    }
}
Topic archived. No new replies allowed.