×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to generate random numbers

Learn, how can we generate random numbers using C++ program?
[Last updated : March 01, 2023]

Generating random numbers in C++

randomize() – this function is used to generate random numbers each time, when you run program.

rand() – this function is used to return random number from 0 to RAND_MAX-1. Here RAND_MAX is the maximum range of the number. If you want to generate random numbers from 0 to 99 then RAND_MAX will be 100.

Both functions are declared in stdlib.h header file, so you have to include this header file in program’s header inclusion section.

Generate random numbers example in C++

// C++ program to generate random numbers

#include <iostream.h>
#include <stdlib.h>

int main()
{
    int i; //loop counter
    int num; //store random number

    //call it once to generate random number
    randomize(); 
    for (i = 1; i <= 10; i++) {
        num = rand() % 100; //get random number
        cout << num << "\t";
    }
    
    return 0;
}

Output

First run:
88 	90	76	3	67	43	20	31	28	1
Second run:
19	89	87	6	99	25	66	29	96	69

If you do not use randomize(), numbers will be generated randomly but when you again run the program same output will come.
the output after removing randomize () :

Output

First run:
66	8	90	99	7	45	15	51	44	80
Second run:
66	8	90	99	7	45	15	51	44	80

Note: always use randomize (), if you want to get random numbers at every run.

In this program, we used # just after about yourself information, because in the program we are using delimiter (#) to terminate string because about yourself section may contain more than one lines, so we have to need a special delimiter to terminate reading.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.