×

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

Different Ways to Compare Strings in C++

This section will go over the many methods for comparing strings in the C++ programming language. The string comparison checks if the first string is equal to another string. HELLO...

6 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

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.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

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.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

C++ vardiac() function

In the C++ programming language, the flexibility feature is provided by the variadic function. To understand more about flexibility, let's see the following syntax. Syntax: If we have to add two numbers,...

3 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.