+ 2

How can i randomly select a value from an array?

like say i have an array with 5 values {1,2,3,4,5} how could i randomly select one of those values and put it in a cout

29th Jun 2017, 10:34 PM
Jubbs
Jubbs - avatar
4 Answers
+ 5
#include <iostream> #include <cstdlib> #include <ctime> int main () srand(time(nullptr)); int arr[ ] = {1, 2, 3, 4, 5}; std::cout << arr[rand()%5]; return 0; }
29th Jun 2017, 11:06 PM
Zeke Williams
Zeke Williams - avatar
+ 4
Zeke, won't that possibly go out of bounds? arr[5] <<<<
29th Jun 2017, 11:38 PM
jay
jay - avatar
+ 3
thanks zeke, that worked.
30th Jun 2017, 12:26 AM
Jubbs
Jubbs - avatar
+ 2
@jay it shouldn't because the remainder of a devision by 5 can never be greater than 4.
30th Jun 2017, 1:34 AM
Zeke Williams
Zeke Williams - avatar