Open In App

rand() and srand() in C++

Last Updated : 13 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

rand() 

rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called. 
The rand() function is used in C++ to generate random numbers in the range [0, RAND_MAX)

Note: If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs.

Syntax: 

int rand(void): 

Parameters:
None

Return value:
rand() returns a pseudo-random number in the range of [0, RAND_MAX). 
RAND_MAX: is a constant whose default value may vary between implementations but it is granted to be at least 32767.

Complexity of rand() function:

Time Complexity: O(1)
Auxiliary Space Complexity: O(1)

Say if we are generating 5 random numbers in C++ with the help of rand() in a loop, then every time we compile and run the program our output must be the same sequence of numbers.

Example:

C++




// C++ program to demonstrate
//  the use of rand()
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main()
{
    // This program will create some sequence of
    // random numbers on every program run
    for (int i = 0; i < 5; i++)
        cout << rand() << " ";
 
    return 0;
}


Output

1804289383 846930886 1681692777 1714636915 1957747793 

NOTE: This program will create same sequence of random numbers on every program run. 

Below program is the implementation of rand() function to get a value from the range 0 to N:

C++




// C++ program to demonstrate the use of rand() to get value
// in a range of 0 to N
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main()
{
    int N = 100;
    // This program will create some sequence of random
    // numbers on every program run within range N
    for (int i = 0; i < 5; i++)
        cout << rand() % N << " ";
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

83 86 77 15 93 

Below program is the implementation of rand() function to get a value from Upper_Bound to Lower_Bound:

C++




// C++ program to demonstrate the use of rand() to get value
// in a range of lb to ub
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main(){
    int lb = 20, ub = 100;
    // This program will create some sequence of random
    // numbers on every program run within range lb to ub
    for (int i = 0; i < 5; i++)
        cout << (rand() % (ub - lb + 1)) + lb << " ";
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

66 90 38 99 88 

srand()

srand() function is an inbuilt function in C++ STL, which is a header file defined in <cstdlib>. srand() is used to initialize random number generators. The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at the program start. Any other value for seed sets the generator to a different starting point. 

Syntax: 

void srand( unsigned seed );
OR
int srand( unsigned int seed);
Seeds the pseudo-random number generator used by rand() with the value seed.

Parameters

seed: A seed for a new sequence of pseudo-random numbers to be returned by successive calls to rand()

Return value

This function returns a pseudo-generated random number.

Note: The pseudo-random number generator should only be seeded once, before any calls to rand(), and at the start of the program. It should not be repeatedly seeded or reseeded every time you wish to generate a new batch of pseudo-random numbers. 

Standard practice is to use the result of a call to srand(time(0)) as the seed. However, time() returns a time_t value which varies every time and hence the pseudo-random number varies for every program call. 
 

rand() and srand() with example

rand() and srand() comparison 


C++




// C++ program to generate random numbers
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
 
int main()
{
    // This program will create different sequence of
    // random numbers on every program run
 
    // Use current time as seed for random generator
    srand(time(0));
 
    for (int i = 0; i < 4; i++)
        cout << rand() << " ";
 
    return 0;
}


Output

1326865685 1413967981 1967280748 919663823 

NOTE: This program will create a different sequence of random numbers on every program run. 

Time complexity: O(N) where N is the number of random numbers to be generated

How srand() and rand() are related to each other?

srand() sets the seed which is used by rand to generate “random” numbers. If you don’t call srand before your first call to rand, it’s as if you had called srand(1) to set the seed to one. 
In short, srand() — Set Seed for rand() Function
 
This article is contributed by Shivam Pradhan.


My Personal Notes arrow_drop_up

Next Article

Similar Reads

Guess Game using rand() and srand() in C
Using srand() and rand() function in C, a simple but interesting game can be made. This game is called "Guess Game" . Rules of the Game : There are three holes . A rat is hidden in one of those three holes.The Rat shuffles its position every time.You have to guess the hole in which the Rat is hidden among the three holes.The hole in which Rat is pr
3 min read
Output of C programs | Set 33 (rand() and srand())
You came across how to generate random numbers and use of two C function rand() and srand() from the article rand() and srand() in C\C++.Listed below are some output related multiple choice question on random numbers.1. Return type of rand() function is: a) short b) int c) char d) float Answer: b Explanation : return type of rand() is integer.2. Th
4 min read
Why Rand() function Always give the Same Value ?
Have you ever wondered why the rand() function always gives the same values each time we compile and run our code? well in this post we are going to discuss this phenomenon in brief. First, let us discuss what is rand() function and what is its property. What is Rand() in C++?rand() function is an inbuilt function in C++ STL, which is defined in he
5 min read
Reduce Array and Maximize sum by deleting one occurrence of A[i] and all occurrences of A[i]+1 and A[i]-1
Given an array A[] having N positive integers, the task is to perform the following operations and maximize the sum obtained while reducing the array: Select an array element (say A[i]) and delete one occurrence of that element and add A[i] to the sum.Delete all the occurrences of A[i]-1 and A[i]+1.Perform these operations until the array is empty.
8 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
Difference and Similarities between PHP and C
PHP is a server-side scripting language designed specifically for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. C is a
3 min read
fesetround() and fegetround() in C++ and their application
fesetround() It sets the specified floating point rounding direction or the "current rounding direction" which is expected to be one of the floating point rounding macros. It is used with rint(), nearbyint() and other rounding functions in C++. Syntax: int fesetround( int round ); where round can be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZE
3 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
Get first and last elements from Array and Vector in CPP
Given an array, find first and last elements of it. Input: {4, 5, 7, 13, 25, 65, 98} Output: First element: 4 Last element: 98 In C++, we can use sizeof operator to find number of elements in an array. // C++ Program to print first and last element in an array #include &lt;iostream&gt; using namespace std; int main() { int arr[] = { 4, 5, 7, 13, 25
2 min read
Similarities and Differences between Ruby and C language
Similarities between Ruby and C There are many similarities between C and Ruby, and some of them are: Like C, in Ruby also… A programmer is able to program procedurally if they like to do. But still, behind the scenes, it will be object-oriented.Both the languages have the same operators, for example, compound assignment and bitwise operators. But
3 min read
Practice Tags :
three90RightbarBannerImg