HIDE NAV

C Pseudo-Random Number Generation

A demostration of rand() to produce different kinds of pseudo-random numbers

randgen.c


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

int main(void) {

	int randNo;

	// seeding random number generator
	// only seed once per program run
	// you will always get the same sequence if you do not seed first
	srand(time(0));

	// all numbers from 0 to RAND_MAX are equally probable
	printf("rand() produces a random integer in the range [0,%d]\n", RAND_MAX);

	// any number within rand range
	randNo = rand();
	printf("rand() output with no modifications: %d\n",randNo);

	// any number in range [0,9]
	randNo = rand() % 10;
	printf("An integer [0,9] inclusive: %d\n",randNo);

	// any number in range [min,max) (note: excludes max)
	int min = 101;
	int max = 105;
	randNo = rand() % (max-min) + min;
	printf("An integer [%d,%d] inclusive: %d\n", min, max-1, randNo);

	// a random double [0,1] (note: includes max)
	double randDouble = (double)rand() / (double)RAND_MAX;
	printf("A double precision floating point number [0,1] inclusive: %f\n", randDouble);

	// if a program needs to execute more than once per second or if reseeding is needed
	// try seeding with srand(time(0)*clock()) instead
	return EXIT_SUCCESS;
}