×

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand().

What exactly is rand()?

The C++ STL's built-in rand() function is defined in the header file cstdlib>. Random numbers are produced using the rand() function. This function is used in our programming to produce random numbers.

For instance, if we are creating a snakes and ladders game in C++ and need to produce any random number between 1 and 6, we can use the rand() function.

Every time this function is used, an algorithm that produces a succession of unrelated numbers is used to generate the random number.

For instance, if we wish to produce a random number between 1 and 6, we would use this function like-

No = rand() % 6 + 1

Syntax:

int rand()
// The return of this function is an integer value between 0 and RAND_MAX.

Program 1:

When we compile and run the program, the result must always be the same sequence of integers, for example, if we are using C or C++ to generate 5 random numbers using the rand() function in a loop.

C Program:

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
   printf("The following are random numbers: ");


  //using for loop


   for(int index = 0; index < 5; index++)


//printing random numbers


      printf(" %d ", rand());
      return 0;
}

C++ Program:

#include <iostream>
#include <cstdlib>
using namespace std;
  
int main()
{
  printf("The following are random numbers: ");
  
  //using for loop
    for(int index = 0; index < 5; index++)
    
    //printing random numbers
    cout << rand() << " ";
    
    return 0;
}

Note: Each time this programme is run, the same random number sequence will be generated.

Output 1:

The outcome of running this code for the FIRST time is

The following are random numbers: 41 18467 6334 26500 19169

Output 2:

The outcome of running this code for the nth time is

The following are random numbers: 41 18467 6334 26500 19169

What is srand() ?

The built-in C++ STL function srand() is defined in the <cstdlib> header file. Random number generators are initialised using the srand() function. The pseudo-random integer series can be created using this function as a preliminary step. As a seed for creating a pseudo-random number, the argument is passed. The pseudo number generator should produce different series of outputs whenever a different seed value is used in srand, just like rand ().

Syntax:

int srand(unsigned seed);

Before any calls to rand() or the beginning of the program, the pseudo-random number generator should only be seeded once. It shouldn't be seeded or reseeded frequently each time you want to produce a fresh set of pseudo-random numbers.

The seed is typically set using the output of a call to srand(time(0)). Though time() returns a time_t value that changes each time, the pseudo-random number changes with each program call.

Program 2:

When we compile and run the program, the result must always be the different sequence of integers, for example, if we are using C or C++ to generate 6 random numbers using the rand() and srand() function in a loop.

C Program:

//Every time you execute this programme, a unique series of random integers will be generated.
#include <stdio.h>
#include <stdlib.h>
#include<time.h>




int main(void)
{
//using current time as the seed for the random number generator	
	srand(time(0));
	
//using loop
	for(int index = 0; index < 6; index++)
	
	//printing random numbers
		printf(" %d ", rand());


	return 0;
}

C++ Program:

//Every time you execute this programme, a unique series of random integers will be generated.


#include <iostream>
#include <cstdlib>
#include<time.h>


using namespace std;


int main(void)
{
//using current time as the seed for the random number generator	
	srand(time(0));
	
//using loop
	for(int index = 0; index < 6; index++)
	
	//printing random numbers
		cout << rand() << " ";


	return 0;
}

Note:

Each time you run this program, a unique random number sequence will be generated.

Output 1:

The outcome of running this code for the 1st time is

27326 13773 5125 17250 32431 14917

Output 2:

The outcome of running this code for the 2nd time is

27735 13836 9922 10509 11033 14238

Output n:

The outcome of running this code for the nth time is

27944 13606 6349 10465 15806 3405

Time Complexity:

The time complexity is: O(n)

What is the relationship between srand() and rand()?

In order for rand to produce "random" numbers, srand() sets the seed. It's as if you had called srand(1) to set the seed to one if you don't call srand before your initial call to rand.

Simply put, srand() sets the seed for the rand() function.


Related Topics

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.