rand() function in C++

In this guide, you will learn what is rand() function is in C++ programming and how to use it with an example.

1. rand() Function Overview

The rand() function is used to generate random numbers in a range from 0 to RAND_MAX. Typically, this function is used in conjunction with the srand() function to seed the random number generator for varying sequences of numbers. It is a part of the C standard library <cstdlib> in C++.

Signature:

int rand(void);

Parameters:

None.

2. Source Code Example

#include <iostream> #include <cstdlib> #include <ctime> int main() { // Seed the random number generator with current time srand(time(0)); // Print 5 random numbers for(int i = 0; i < 5; i++) { std::cout << "Random number " << (i+1) << ": " << rand() << std::endl; } return 0; } 

Output:

(Randomized output every execution. An example might look like:) Random number 1: 2083453501 Random number 2: 176128037 Random number 3: 621356489 Random number 4: 123456789 Random number 5: 987654321 

3. Explanation

1. Before generating random numbers, it's essential to seed the random number generator using srand(). Seeding it with the current time by passing time(0) ensures a different sequence of random numbers every time the program is executed.

2. We then use the rand() function in a loop to generate and print 5 random numbers.

3. Each time rand() is called, it returns a pseudo-random number between 0 and RAND_MAX.


Comments