### 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.

 ``123456789101112131415161718192021222324`` ``````#include #include #include using namespace std; int main (){ int x; cin >> x; cout << "\n"; int y[x]; srand(time(0)); for(int i=0;i> 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
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

 ``12345678910111213141516171819202122232425`` ``````#include #include #include using namespace std; int main (){ int x; cin >> x; cout << "\n"; int y[x]; srand(time(0)); for(int i=0;i> y[i]; } for(int i=0;i
Topic archived. No new replies allowed.