Can I get a random value from an array?

Example:

then make it print outCode:`char vals[5]={'3','350','400','44','2'};`

3, 350, 400, 44, or 2 at random?

Printable View

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

Example:

Code:`char vals[5]={'3','350','400','44','2'};`

3, 350, 400, 44, or 2 at random? - 05-09-2002jdinger
use rand()%5 to give you the numbers 0 to 4. Then grab that element from your array.

- 05-09-2002XeiYes
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-2002blight2c
sure,

Code:`rand() % array_size_-1`

- 05-09-2002Viciouslike 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-2002XeiYou 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-2002ViciousNICE
Sweet... thx for the quick help all.

- 05-09-2002UnregisteredCode:
`char test[5]={'2','5','20','38','24'};`

int x;

srand((unsigned)time(NULL));

x=rand()%5;

cout<<test[x];

- 05-10-2002ErionD
rand()%4 will return 0-3. If you have 4 items in your array use rand()%5

- 05-10-2002Viciousbut.....
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-2002linuxgeek
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 . . .