FAQ > Generate random numbers?


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 1) > Generate random numbers?

This item was added on: 2003/01/08

In order to generate a pseudo-random number you can use the rand() function that is defined in stdlib.h (or cstdlib for C++). This will return you a number between 0 and RAND_MAX (also defined in stdlib.h), which is guaranteed to be at least 32767.

If you want to get different random numbers each time you run your program, you will also need to use the srand() function as well, as this will seed the generator. The srand() function is called only once during a programs execution.

The prototypes for these two functions are:

#include <stdlib.h>
int rand(void);
void srand(unsigned int seed);

The number you pass as the parameter to srand() will seed the generator. Passing the same number each time will cause the same set of random numbers to be generated. To get different random number set, pass a different seed. The most common way to achieve this is by calling the time() function and passing its result to srand().

A simple example of this is:


/*
 * This code is written in C, but it could just as easily be done in C++.
 * The rand() and srand() functions are available in both languages.
 */
 
#include <stdio.h>  
#include <stdlib.h>  
#include <time.h>  

int main(void)
{
  int i;
  
  srand(time(NULL));
  
  i = rand();
  
  printf ("Your random number is %d\n", i);  

  printf ("This compiler can generate random numbers from 0 to %d\n", RAND_MAX);

  return(0);
}


And now a C++ version of the same thing.


#include <iostream>   
#include <ctime>   

int main(void)
{
  int i;    
  
  srand(time(NULL));    
  i = rand();  
  std::cout <<"Your random number is " <<i <<std::endl;  
  std::cout <<"This compiler can generate random numbers from 0 to " 
            <<RAND_MAX <<std::endl;
  
  return(0);
}


To generate numbers in a specific range, you have to use some simple maths. First, start by limiting the highest number that the calculation will return. This will provide the ability to create a random number between 0 and N. Once done, to get random numbers between higher ranges, simply add the minimum value to the returned number.

It's best to encapsulate this process in a function so that it can be called as many times as required.


#include <stdio.h> 
#include <stdlib.h> 

int GetRand(int min, int max);

int main(void)
{
  int i, r;
  
  for (i = 0; i < 20; i++)
  {
    r = GetRand(10, 12);
    printf ("Your number is %d\n", r);
  }
  
  return(0);
}

int GetRand(int min, int max)
{
  static int Init = 0;
  int rc;
  
  if (Init == 0)
  {
    /*
     *  As Init is static, it will remember it's value between
     *  function calls.  We only want srand() run once, so this
     *  is a simple way to ensure that happens.
     */
    srand(time(NULL));
    Init = 1;
  }

  /*
   * Formula:  
   *    rand() % N   <- To get a number between 0 - N-1
   *    Then add the result to min, giving you 
   *    a random number between min - max.
   */  
  rc = (rand() % (max - min + 1) + min);
  
  return (rc);
}


The changes needed to make the previous example into a C++ program are minimal, only the headers and main need to change, as is shown here:


#include <iostream> 
#include <ctime> 

int main(void)
{
  int i, r;

  for (i = 0; i < 20; i++)
  {
    r = GetRand(10, 12);
    std::cout <<"Your number is " <<r <<std::endl;
  }

  return(0);
}


It should be noted that the formula shown here is apparently not the best, although it may be the simplest to understand. To learn more, take a look at this FAQ entry and this article.

Script provided by SmartCGIs