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

 Live Demo

#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

 Live Demo

#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

Updated on: 25-Jun-2020

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements