w3resource

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


Follow us on Facebook and Twitter for latest update.