Generate random number between 1 to 100 in C++
In this tutorial, we will see how to generate a random number between 1 to 100 in C++.
rand( ) function in C++
It’s an inbuilt function in c++, which returns a random number between 0 and RAND_MAX.
If we use rand( )%n, it returns a random number 0 to n-1 (both inclusive).
Now here we want a random number between 1 and 100, we will use 1 + rand( )%100.
C++ Code: Generate random number between 1 to 100
#include <bits/stdc++.h> using namespace std; int main(){ cout << "A random number between 1 and 100: " << 1 + (rand() % 100) << endl; }
Output
A random number between 1 and 100: 100
srand( ) function
This is used to set the starting point with seed for producing the pseudo-random numbers. If you want a different random number each time, paste “srand(time(0));” in the code. And don’t forget to import “#include <time.h>” header.
Output 1
A random number between 1 and 100: 3
Output 2
A random number between 1 and 100: 26
Also read: Pick a random element from an array in C++
Leave a Reply