Generating "Random" Numbers

In computer science, the generation of truly random numbers is a significant challenge, the exploration of which is beyond the scope of this class. (Just remember that some methods of picking random numbers with a computer are better than others. Even in C, there are better functions than rand(), but we'll stick with the basics for now. For a more detailed discussion, head over to random.org.)

Most of the time, we generate what are actually pseudo-random numbers, which are predictable sequences created by a mathematical formula. Better generators make it difficult to guess the next number based on the previous numbers seen. We can make them seem more random by starting the sequence at different points, using a number that will be different each time the program starts as its "seed" ... or starting point. Once that seed has been selected (usually only done once for each time the program starts), you can request a "random" number from the sequence every time you need a new number. In C, we usually use the current time to set the seed for the random number generation function called rand().

So to make your program seem to act randomly in C, you need to do three things:

  1. Make sure you include two libraries needed to get the time and to use the randomizing functions: <time.h> and <stdlib.h>.
  2. Run the function that "seeds" the randomizer. This function is called srand(), and it should only be run ONCE at the beginning of the main program (kinda like connecting to the robot, but you don't need to disconnect in this case).
  3. Run the function rand() every time you want a new number. The rand() function by itself produces a number between 0 and a maximum value specified by the system (known by the macro RAND_MAX). We can use the modulo operator to set the range that we want for our program. See King pages 172 - 174 or guess_my_num.c for examples.