# Discrepancy using rand() and array.

This is a discussion on Discrepancy using rand() and array. within the C Programming forums, part of the General Programming Boards category; I've made the following function. Code: void select(int deck[52]) { srand(time(NULL)); //Seeds the randomization int random = rand() % 52; ...

1. ## Discrepancy using rand() and array.

Code:
```void select(int deck[52])
{
srand(time(NULL)); //Seeds the randomization
int random = rand() % 52; //Puts a random value in the variable random.
int selected;
printf("\n%d\n", random);
selected = deck[random];
printf("\n%d\n", selected);

}```
The problem is that e.g. it printed it had used 50 as the random value. The corresponding deck-card would be: 12. It gives me 13, however.

I thought that the rand() function would give me values from 1 and up (correct?)?

Thank You.

2. Nope, it starts at 0:
Originally Posted by MSDN
The rand function returns a pseudorandom integer in the range 0 to RAND_MAX (32767).

3. The range of rand() is [0, RAND_MAX].

4. In other words, both 0 and RAND_MAX might be returned by rand().

Note that srand() should only be called once during the execution of a program, so you should probably put it in an initialization function of some sort.

5. Even if rand() gave you values of one or greater, when you take the modulus of that number, zero will still be one of the outcomes. E.g. 52 % 52 equals zero.

Also, you need to make sure that you only call srand once in your entire program, or rand() will not work correctly! Best to put it at the start of main rather than in a function that can be called more than once.

6. Originally Posted by iMalc
Even if rand() gave you values of one or greater, when you take the modulus of that number, zero will still be one of the outcomes. E.g. 52 % 52 equals zero.
Yes . . . rand() % N will give you N possible numbers, from 0 to N-1 inclusive. In other words, rand() % 4 might give you 0, 1, 2, or 3. One way of looking at it is the number you use for the modulus is just like the number you use to declare an array.
Code:
```int array[5] = {1, 2, 3, 4, 5};

printf("%i\n", array[rand() % 5]);```
Also, you need to make sure that you only call srand once in your entire program, or rand() will not work correctly! Best to put it at the start of main rather than in a function that can be called more than once.