Search This Blog

How to Get Random Number in C

C Language has functions to generate random numbers. It is not actually random number. Computer cannot generate real random number. Rather they produce pseudo random number. We will see later in another post how pseudo random number generator work. In this post, we will see how to use pseudo random number generation functions in C.

The function rand() is used to get random number. The random numbers generated by the function depend on a an initial 'seed'. We may use time as seed here. We will give current time as initial seed by calling srand() function. Calling time(NULL) will return current time. It is in time.h library. Thus srand(time(NULL)) will set initial seed as current time. As we call rand(), we will get different random numbers. The random numbers start from zero (inclusive). To set a maximum value for random number, we may use the % operator.


rand()%10 returns random number from 0 to 9 (inclusive).
rand()%50 returns random number from 0 to 49 (inclusive).
rand()%51 returns random number from 0 to 50 (inclusive).
rand()%101 returns random number from 0 to 100 (inclusive).

Therefore we may say,
rand()%max returns random number from 0 to max-1.

To get random number from 50 to 99 (inclusive):
use 50+rand()%(100-50)

In general, to get a random number from min to max (including min and max) use the following code:

min+rand()%(max+1-min)


#include<stdio.h> #include<stdlib.h> #include<time.h> main() { int min,max,rnum,i; printf("Enter the minimum and maximum value of random number"); scanf("%d%d",&min,&max); printf("Five random numbers from %d to %d are :\n",min,max); srand(time(NULL)); for(i=0;i<5;i++) printf("%d, ",min+rand()%(max+1-min)); getch(); }

No comments: