80 likes | 194 Views
Functions. Dilshad M. Shahid New York University @1999. Today. Random number generation. Random Number Generation. There is a function called rand which will generate random numbers rand returns an integer value so you could call it in this way: i = rand(); /* i is of type int */
E N D
Functions Dilshad M. Shahid New York University @1999
Today • Random number generation
Random Number Generation • There is a function called rand which will generate random numbers • rand returns an integer value so you could call it in this way: i = rand(); /* i is of type int */ • rand function generates an integer between 0 and RAND_MAX • RAND_MAX is a symbolic constant defined in <stdlib.h> header file. rand itself is in <stdlib.h> which you will have to include in your program if you want to use the rand function
Random Number Generation • Since rand() produces such large numbers we often use the following to scale it down, e.g. : rand() % 6 • This would produce (in this case) numbers between 0 and 5 (all the possible remainders when any number is divided by 6) • Similarly, rand() % 4 would return numbers between 0 and 3
Random Number Generation • If you run a program containing the rand function you will notice the same output each time you run it • How come, if rand is generating random numbers? • The truth is rand actually generates pseudo-random numbers
Random Number Generation • To actually produce a different sequence of numbers, it has to be conditioned • This is called randomizing and we use the standard library function srand • srand takes an unsigned integer argument and seeds the rand function
Random Number Generation • An unsigned int is stored in at least 2 bytes of memory (like a regular int) but can only have a positive value between 0 and 65535 • An int can have both positive and negative values between -32767 and +32767 • srand is also in <stdlib.h>
Random Number Generation • Check out the 2 examples with rand and srand on the web page. • Please read the comments in the program examples carefully.