In this article, we will discuss the working principle, syntax and examples of rand() and srand() functions in C STL.
rand() function is a built-in function in C STL and is defined in the
Just like when we make ludo game in C, we have to generate any random number between 1 and 6 so we can use rand () to generate random numbers.
Random numbers are generated by using an algorithm that gives a series of unrelated A number is generated whenever this function is called.
Just like we want to generate a random number between 1-6, we can use this function like -
Num = rand() % 6 1;
int rand();
This function does not accept parameters -
This function returns an integer value between 0 and RAND_MAX.
Input
rand() % 100 +1;
Output
57
rand()
Live Demo
#include <stdio.h> #include <stdlib.h&g; int main(void){ printf("Randomly generated numbers are: "); for(int i = 0; i<5; i++) printf(" %d ", rand()); return 0; }
If we run this code for the first time, the output will be -
Randomly generated numbers are: 1804289383 846930886 1681692777 1714636915 1957747793
If we run this code for the Nth time , the output will be -
Randomly generated numbers are: 1804289383 846930886 1681692777 1714636915 1957747793
srand() function is a built-in function in C STL and is defined in the
int srand(unsigned int seed);
The function accepts the following parameters -
Seed - This is pseudo The integer used as seed for the random number generator.
This function returns a pseudo-generated random number.
Input
srand(time(0)); rand();
Output
1804289383
srand()
Live Demo
#include <stdio.h> #include <stdlib.h> #include<time.h> int main(void){ srand(time(0)); printf("Randomly generated numbers are: "); for(int i = 0; i<5; i++) printf(" %d ", rand()); return 0; }
If we run this code for the first time, the output will be -
Randomly generated numbers are: 382366186 1045528146 1291469435 515349891 931606430
If we run this code for the second time , the output will be -
Randomly generated numbers are: 1410939666 214525217 875042802 1560673843 782892338
The above is the detailed content of In C/C++, rand() and srand() are translated as follows:. For more information, please follow other related articles on the PHP Chinese website!