- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Use rand and srand Functions
Random numbers can be generated in C++ using the rand() function. The srand() function seeds the random number generator that is used by rand().
A program that uses rand() and srand() is given as follows −
Example
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main() { srand(1); for(int i=0; i<5; i++) cout << rand() % 100 <<" "; return 0; }
Output
The output of the above program is as follows −
83 86 77 15 93
In the above program, the output will be same on every program run as srand(1) is used..
To change the sequence of random numbers at every program run, srand(time(NULL)) is used.A program to demonstrate this is given as follows −
Example
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main() { srand(time(NULL)); for(int i=0; i<5; i++) cout << rand() % 100 <<" "; return 0; }
Output
The output of the above program is as follows −
63 98 17 49 46
On another run of the same program, the output obtained is as follows −
44 21 19 2 83
Advertisements
To Continue Learning Please Login
Login with Google