Answer: GNU provides facilities for generating ‘pseudo-random numbers’. These aren’t truly random; sequence of numbers generated repeats periodically, though, over a large period so that we generally ignore this. Where, actually, we need to use such numbers implies situations, like games of chance, simulations etc., where we want to generate unpredictable sequences of numbers each time program is run. Random number generator works by remembering the seed value which it uses to compute next random number and also to compute new seed.
Though, sequence of numbers generated isn’t predictable when the program executes once. But it generates the same sequence of numbers each time program is run. This is because initial seed is always the same. To obtain, different set of numbers each time program is run, give new seed value to random-number generator. Basing the seed value on current time works well! Following two functions are used for generating pseudo-random numbers.
int rand(void); void srand(unsined int SEED);
Notice that ‘rand()’ function generates numbers in range 0 through RAND_MAX. To obtain pseudo-random numbers from smaller range, take “rand() modulo size-of-desired-range” and scale it by adding or subtracting an offset value.
‘srand()’ function establishes SEED argument as new seed value for random number generator each time program is run. If ‘rand()’ function is called before establishing seed value with srand(), it uses the seed value as 1. Let’s experiment by writing a simple C program using above functions to understand random numbers.
/* rand_with_seed.c -- srand() establishes seed value for rand() */ #include <stdio.h> #include <stdlib.h> #define MY_RANGE 20 int main(void) { int i; srand(time(0)); printf("Sequence of Pseudo-Random Numbers:\n"); for (i = MY_RANGE; i >= 0; i--) printf("%d ", rand() % MY_RANGE); printf("\n"); return 0; }
Let’s oserve the output below
Sequence of Pseudo-Random Numbers: 1 12 1 13 1 2 1 6 14 19 14 1 5 18 17 10 7 4 4 12 3 Sequence of Pseudo-Random Numbers: 14 16 11 5 8 18 10 4 16 13 11 12 9 19 6 3 7 1 0 3 15 Sequence of Pseudo-Random Numbers: 10 5 3 19 11 4 10 11 2 19 19 2 9 2 8 15 16 19 18 4 6 Sequence of Pseudo-Random Numbers: 10 5 3 19 11 4 10 11 2 19 19 2 9 2 8 15 16 19 18 4 6 Sequence of Pseudo-Random Numbers: 6 13 15 14 0 14 7 5 19 9 19 12 13 4 0 17 19 17 7 6 0
Notice that in above program, seed value established with ‘srand()’ prior to calling ‘rand()’ each time program was run, different sequence of random numbers generated. Additionally, I took ‘rand() modulo size-of-desired-range’ to obtain pseudo-random numbers from smaller range.
Try experimenting the same program without calling the ‘srand()’ and observe the output! Isn’t this
interesting!
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice BCA MCQs
- Apply for Computer Science Internship
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Check C Books