Site icon TestingDocs.com

Generate Random Numbers in C++ program

Introduction

In this post, we will discuss how to generate random numbers in C++ programs. C++ stdlib library provides us useful functions in generating random number sequences. rand() function when invoked returns a uniform random number from 0 to RAND_MAX interval.

Code Listing

Sample c++ program that generates 10 random numbers.

/*******************************
* Display 10 random numbers
*******************************/
#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    for(int i=0; i< 10; i++)
    {
        cout << rand() << endl;
    }
    return 0;
}

 

Program output:

41
18467
6334
26500
19169
15724
11478
29358
26962
24464

Process returned 0 (0x0) execution time : 4.293 s
Press any key to continue.

Run the program another time and check the output. rand() function always produces the same random number sequence.

srand()

To produce different random numbers we can use srand() function.To this function you can set a seed value to produce different random numbers. seed should be different for each run of the program. For example, we can use current time as seed value. time(0) gives the current time. srand() expects the seed as unsigned int.

/*******************************
* Display 10 random numbers for
* every run of the program.
*******************************/
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

int main()
{
    srand((unsigned int) time(0));
    for(int i=0; i< 10; i++)
    {
        cout << rand() << endl;
    }
    return 0;
}

Run 1:

9748
27688
3520
32299
23361
28456
20331
17007
14059
5648

Process returned 0 (0x0) execution time : 2.785 s
Press any key to continue.

*********************

Run 2

10150
6254
5357
10199
14102
19924
9947
17400
13369
3099

Process returned 0 (0x0) execution time : 0.450 s
Press any key to continue.

The IDE used in the tutorial is Code:: Blocks. To download and install Code Blocks follow the link:

https://www.testingdocs.com/download-and-install-codeblocks/

For more information on Code Blocks IDE, visit the official website of Code blocks IDE:
http://www.codeblocks.org/

Exit mobile version