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

CC++Server Side ProgrammingProgramming

In this article, we will be discussing the working, syntax, and examples of rand() and srand() function in C++ STL.

What is rand()?

rand() function is an inbuilt function in C++ STL, which is defined in <cstdlib> header file. rand() is used to generate a series of random numbers. We use this function when we want to generate a random number in our code.

Like we are making a game of ludo in C++ and we have to generate any random number between 1 and 6 so we can use rand() to generate a random number.

The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.

Like we want to generate a random number between 1-6 then we use this function like −

Num = rand() % 6 + 1;

Syntax

int rand();

Parameters

The function accepts no parameter(s) −

Return value

This function returns an integer value between 0 to RAND_MAX.

Input 

rand() % 100 +1;

Output 

57

Example

rand()

 Live Demo

#include <stdio.h>
#include <stdlib.h&g;
int main(void){
   printf("Randomly generated numbers are: ");
   for(int i = 0; i<5; i++)
      printf(" %d ", rand());
   return 0;
}

Output

If we run this code for the FIRST time output will be −

Randomly generated numbers are: 1804289383 846930886 1681692777 1714636915
1957747793

If we run this code for the Nth time output will be −

Randomly generated numbers are: 1804289383 846930886 1681692777 1714636915
1957747793

What is srand()?

srand() function is an inbuilt function in C++ STL, which is defined in <cstdlib> header file. srand() is used to initialise random number generators. This function gives a starting point for producing the pseudo-random integer series. The argument is passed as a seed for generating a pseudo-random number. Whenever a different seed value is used in srand the pseudo number generator can be expected to generate different series of results the same as rand().

Syntax

int srand(unsigned int seed);

Parameters

The function accepts the following parameter(s) −

  • seed − This is an integer that is used as seed by pseudo-random number generator.

Return value

This function returns a pseudo generated random number.

Input 

srand(time(0));
rand();

Output 

1804289383

Example

srand()

 Live Demo

#include <stdio.h>
#include <stdlib.h>
#include<time.h>
int main(void){
   srand(time(0));
   printf("Randomly generated numbers are: ");
   for(int i = 0; i<5; i++)
      printf(" %d ", rand());
   return 0;
}

Output

If we run this code for the FIRST time output will be −

Randomly generated numbers are: 382366186 1045528146 1291469435 515349891
931606430

If we run this code for the SECOND time output will be −

Randomly generated numbers are: 1410939666 214525217 875042802
1560673843 782892338
raja
Published on 22-Apr-2020 16:01:15
Advertisements