Random Integers in C
Generate random integers in C.
Pseudo-random sequence generation from stdlib.h.
int rand(void) | generates a pseudo-random number |
void srand(unsigned int seed) | set the rand() pseudo-random generator seed [common convention uses time() to seed] |
Example: Random Integers in C
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
//Set the rand() pseudo-random generator seed [common convention uses time() to seed]
srand(time(NULL)); // Initialization, should only be called once.
for (int i = 0; i < 5; ++i)
{
int r = rand(); // Generates a pseudo-random number
printf("\n%d", r);
}
}
Output:
12277 1435 25678 14705 30146
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/c-snippets/how-to-generate-a-random-int-in-c.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics