Tuesday, May 11, 2010

Random Number between two integers in C

Finding out a RANDOM NUMBER bettween two integers a & b in C Language:

We are aware of the rand() function:

rand() calculates and returns the pseudo-random integer in the range 0 to RAND_MAX
where RAND_MAX is a constant defined in . Its default value may vary between implementations but it is granted to be at least 32767.

Step by Step Solution:
result = rand() % b;// result lies in between 0 and (b-1)
result = ((rand() % b) + a);// result lies in between a and (a+(b-1))
result = ((rand() % ((b+1)-a)) + a);// result lies in between a and b

From the third solution the minimum value of the random number will be (0+a) = a, and maximum value of the random number will be (b-a+a) = b.

No comments:

Post a Comment