C++ Program to Generate Random Numbers

In this C++ program, we generate N random numbers between 1 to 1000 using rand function. This program takes N as input from user and print N space separated random numbers on screen.

  • The rand function of cstdlib standard library returns a pseudo-random number in the range of 0 to RAND_MAX, where RAND_MAX is a environment dependent value which is the maximum value returned by rand function.
  • To generate random numbers between 1 to 1000, we will evaluate rand()%1000, which always return a value between 0 to 999. We will add 1 to this value to get a number between 1 to 1000.
  • The probability of selection of any number between 1 to 1000 is 1/1000 or 0.001.

C++ Program to Generate Random Numbers using Rand Function

// C++ program to print N random numbers between 1 to 1000

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int main() {
    int n, random;
    cout << "Enter number of random numbers\n";
    cin >> n;
 
    // print n random numbers using rand function
    cout << "Random numbers between 0 to 1000\n";
    while(n--){
        random = rand()%1000 + 1;
        cout << random << " ";
    }
    
    return 0;
}
Output
Enter number of random numbers
7
Random numbers between 0 to 1000
42 764 431 831 335 170 501

In above C++ program, we first take the count of random numbers as input from user and store it in variable "n". The using a while loop, we call rand function "n" times to generate random number between 1 to 1000 and print it on screen.