# Help with Random...

• 05-09-2002
Vicious
Help with Random...
Can I get a random value from an array?

Example:

Code:

`char vals[5]={'3','350','400','44','2'};`
then make it print out
3, 350, 400, 44, or 2 at random?
• 05-09-2002
jdinger
use rand()%5 to give you the numbers 0 to 4. Then grab that element from your array.
• 05-09-2002
Xei
Yes
You can get a random value from an array. What I would do is randomize an Integer from 0 to (whatever index) then just access that array using index X. So like: val[x]; where x will be your randomized variable.
• 05-09-2002
blight2c
sure,
Code:

`rand() % array_size_-1`
do you know about the rand() function, seeding, and all that stuff. if not check the faq. did that answer your question? :)
• 05-09-2002
Vicious
like this?
Code:

```char test[5]={'2','5','20','38','24'}; srand(time(NULL)); test = rand() % 4; cout<<test;```
????
If thats not right pls give example
• 05-09-2002
Xei
You got it!
Yes that is a correct method of randomization. However that will not display the index. Here is how I would do it:

#include "time.h"

...
INT x;
srand(time(NULL));
x = rand()%4;
cout<<test[x];
• 05-09-2002
Vicious
NICE
Sweet... thx for the quick help all.
• 05-09-2002
Unregistered
Code:

```  char test[5]={'2','5','20','38','24'};   int x;   srand((unsigned)time(NULL));   x=rand()%5;   cout<<test[x];```
• 05-10-2002
ErionD
rand()%4 will return 0-3. If you have 4 items in your array use rand()%5
• 05-10-2002
Vicious
but.....
If I have 5 items in an array, it should be
rand()%4

that will get 0 - 4

0, 1, 2, 3, 4, <--- That is 5 numbers

:confused:
• 05-10-2002
linuxgeek
Nope, %4 will give 0,1,2,3. Modulus is the remainder of the fraction.

1/4 = 0 with 1 as the modulus
2/4 = 0 with 2 as the modulus
3/4 = 0 with 3 as the modulus
4/4 = 1 with 0 as the modulus
5/4 = 1 with 1 as the modulus
6/4 = 1 with 2 as the modulus

etc . . .