rand() and srand() Functions in C

This is a C Program to generate random numbers within given range. This version of code uses rand() and srand() functions. The function srand() is used to initialize the pseudo-random number generator and rand() function generates a pseudo random number.

Here is the source code of the C program to use rand and srand functions. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  5. int main(void)
  6. {
  7.     int num;
  8.     /* Seed number for rand() */
  9.     srand((unsigned int) time(0) + getpid());
  10.     printf("\nGenerating a random number using srand and rand function.\n");
  11.     num = rand();
  13.     printf("%d\n", num);
  15.     return EXIT_SUCCESS;
  16. }

$ gcc random.c -o random
$ ./random
Generating a random number using rand and srand functions.

Sanfoundry Global Education & Learning Series – 1000 C Programs.


Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.