C++ Program to Generate Random Numbers

In this post, we will learn how to generate random numbers using C++ Programming language.

This program asks the user to enter the upper limit. Then, it generates a random number with the help of the rand() function.

So, without further ado, let’s begin this tutorial.

C++ Program to Generate Random Numbers

// C++ Program to Generate Random Numbers
#include <iostream>
#include <cstdlib>

using namespace std;
int main(){
    int max;
    
    // Asking for input
    cout << "Enter the upper limit: ";
    cin >> max;
    
    srand(time(0));
    cout << "The random number is: " << rand() % max;
    return 0;
}

Output 1

Enter the upper limit: 25
The random number is: 18

Output 2

Enter the upper limit: 25
The random number is: 15

How Does This Program Work ?

    int max;

In this program, we have declared an int data type variable named max.

    // Asking for input
    cout << "Enter the upper limit: ";
    cin >> max;

Then, the user is asked to enter an upper limit. The value of the upper limit gets stored in the max named variable.

    srand(time(0));
    cout << "The random number is: " << rand() % max;

We generate random numbers with the help of the rand() function. srand() function is used to take the initial value which is then used by rand() to generate random numbers.

Rand() function is used to generate random numbers. rand() % max is used to generate random numbers between the initial value and the final value.

Conclusion

I hope after going through this post, you understand how to generate random numbers using C++ Programming language.

If you have any doubt regarding the program, feel free to ask your query in the comment section. We will be delighted to solve your query.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *