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.
Please read the FAQ about this.
I did just mention that, but I guess it's important enough to be repeated.