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 <iostream>
  2. #include <cstdlib>
  3. #include <time.h>
  4.  
  5. const int LOW = 1;
  6. const int HIGH = 32000;
  7.  
  8. using namespace std;
  9.  
  10. int main()
  11. {
  12.     int randomNumber;
  13.     time_t seconds;
  14.     time(&seconds);
  15.     srand((unsigned int) seconds);
  16.     for (int i = 0; i < 10; i++)
  17.     {
  18.         randomNumber = rand() % (HIGH - LOW + 1) + LOW;
  19.  
  20.         cout << randomNumber << " ";
  21.     }
  22.     cout << "...";
  23.     return 0;
  24. }

Output:

$ g++ RandomizedSequenceOfNumbers.cpp
$ a.out
 
312 7423 23444 16008 31816 1823 29315 17424 11753 18384 ...

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.