C Program to Generate Random Numbers in a Range

This is a C Program to generate random numbers within given range. This version of code uses rand() and srand() functions.

Here is source code of the C Program to Generate Randomized Sequence of Given Range of Numbers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. const int LOW = 1;
  6. const int HIGH = 32000;
  7.  
  8. int main() {
  9.     int randomNumber, i;
  10.     time_t seconds;
  11.     time(&seconds);
  12.     srand((unsigned int) seconds);
  13.     for (i = 0; i < 10; i++) {
  14.         randomNumber = rand() % (HIGH - LOW + 1) + LOW;
  15.  
  16.         printf("%d ", randomNumber);
  17.     }
  18.     printf("...");
  19.     return 0;
  20. }

Output:

$ gcc RandomizedSeqOfNumbers.cpp
$ ./a.out
 
24874 17738 3972 19634 646 5665 1147 9374 3726 3556 ...

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

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

advertisement
advertisement
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.