Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rand
srand
c++
functions

What are the rand and srand functions in C++?

Educative Answers Team

The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.

svg viewer

Both of the functions are defined in the header:

#include <cstdlib>

Code

In the code below, the rand() function is used without seeding. Therefore, every time you press the run button, ​it generates the same number.

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
  int i = rand();
  cout << i;
}

Let’s try using both of the functions together to see how it generates a different number after every click.

Note: The standard practice is to use the return value of time(0) function as the seed.

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
  srand(time(0));
  int i = rand();
  cout << i;
}

RELATED TAGS

rand
srand
c++
functions
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring