Is it possible to generate random number in C programming language ? If yes then please explain how ?
rand() and srand() in C/C++
rand ()
rand() function is used in C to generate random numbers. If we generate a sequence of random number with rand() function, it will create the same sequence again and again every time program runs. Say if we are generating 5 random numbers in C with the help of rand() in a loop, then every time we compile and run the program our output must be the same sequence of numbers.
Syntax:
int rand(void):
returns a pseudo-random number in the range of 0 to RAND_MAX.
RAND_MAX: is a constant whose default value may vary
between implementations but it is granted to be at least 32767.
// C program to generate random numbers
#include <stdio.h>
#include <stdlib.h>
// Driver program
int main(void)
{
// This program will create same sequence of
// random numbers on every program run
for(int i = 0; i<5; i++)
printf(" %d ", rand());
return 0;
}
NOTE: This program will create same sequence of random numbers on every program run.
Output 1:
453 1276 3425 89
Output 2:
453 1276 3425 89
Output n:
453 1276 3425 89
Didn't get the answer.
Contact people of Talent-C Language directly by clicking here