CS19002 Programming and Data Structures

Autumn/Spring semester

How to generate random numbers

First include the header file:
#include <stdlib.h>
The built-in routine rand() returns a random positive integer.
int randInt;
...
randInt = rand();
In order to generate random numbers between 0 and a bound B use the following:
int randInt;
int B = 10;
...
randInt = rand() % (B+1);
In order to generate random numbers between -B and +C use the following:
int randInt;
int B = 10;
int C = 20;
...
randInt = ( rand() % (B+C+1) ) - B;

Random number generators depend on some seed value. Every time you run a C program, the seed is initialized to a predetermined value and thus you always get the same sequence of random numbers. If you want different sequences during different runs, use the specific function srand to seed the random number generator by a value of your choice. It is often useful to seed using the current time:

srand((unsigned int)time(NULL));
Do this only once at the beginning of main.


[Course home] [Home]