Home | | Computer Science 11th std | C++ Function: Generating Random Numbers

Chapter: 11th Computer Science : Chapter 11 : Functions

C++ Function: Generating Random Numbers

The srand() function in C++ seeds the pseudo random number generator used by the rand() function.

Generating Random Numbers

 

The srand() function in C++ seeds the pseudo random number generator used by the rand() function. The seed for rand() function is 1 by default. It means that if no srand() is called before rand(), the rand() function behaves as if it was seeded with srand(1). The srand() function takes an unsigned integer as its parameter which is used as seed by the rand() function. It is defined in<cstdlib>or <stdlib.h>header file.

 

Program 11.15

#include<iostream>

#include<cstdlib.h>

using namespace std;

int main()

{

      int random = rand(); /* No srand() calls before rand(), so seed = 1*/

      cout << "\nSeed = 1, Random number = " << random; srand(10);

      /* Seed = 10 */

      random = rand();

      cout << "\n\nSeed = 10, Random number = " << random;

      return 0;

}

OUTPUT :

Seed = 1, Random number = 41

Seed = 10, Random number = 71

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 11 : Functions : C++ Function: Generating Random Numbers |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.