rand() and srand() Functions in C++

This is a C++ Program to make use of Rand and Srand functions to generate unique random numbers.

Here is 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 <iostream>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. using namespace std;
  6.  
  7. int main(int argc, char **argv)
  8. {
  9.     cout << "First number: " << rand() % 100;
  10.     srand(time(NULL));
  11.     cout << "\nRandom number: " << rand() % 100;
  12.     srand(1);
  13.     cout << "\nAgain the first number: " << rand() % 100;
  14.     return 0;
  15. }

Output:

$ g++ RandSrandFunctions.cpp
$ a.out
 
First number: 41
Random number: 98
Again the first number: 41

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.