“Random” between limits

Many algorithm correctness and performance tests, games and others require random number generation. Here is a way to generate a random number between two limits min and max.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()

{

int randomnum;
int min=1;  /* lower limit */
int max=7; /*upper limit */

time_t seconds;
time(&seconds);
srand((unsigned int) seconds);  /*seed for rand() */

randomnum = rand() % (max-min+1) + min; /*generate random number within limits*/

printf(“random number=%d\n”,randomnum);

return 0;

}

The idea behind the solution is very simple.

  • rand() generates a random integer between 0 and RAND_MAX. The number generated depends on the seed
  • rand()%max+1 generates an integer between 1 and max
  • On the same lines, rand()%(max-min+1) generates a random number between 0 and (max-min) thereby randomizing the difference between the two limits. To this random difference, we can add a lower limit min to generate the random integer between min and max