How to generate random numbers between 1 to 10 in C++?
In this short tutorial, I am going to show how to generate random numbers between 1 to 10 in C++.
For our examples, we will use the rand() function.
The rand() function:
- Is a built-in function in C++ Standard Library
- Defined in the <cstdlib> header file
Generate one random number between 1 to 10
In this program, we will generate one random number between the range of 1 and 10 (inclusive). Have a look at the code and sample output:
#include<iostream> #include<cstdlib> #include <time.h> using namespace std; int main(){ // Providing a seed value srand((unsigned) time(NULL)); //Range is given between 1 to 10 (inclusive) int random = 1 + (rand() % 10); cout <<"Random Number = " <<random<<endl; return 1; }
A sample output:
C++ program to generate and display 5 random numbers between 1 and 10
In this program, we will use a for loop to generate random numbers between 1 and 10.
In the for loop, we have set the condition to run the code five times.
In the for loop body, we used the rand() function where we specified the range of 1 to 100.
#include<iostream> #include<cstdlib> #include <time.h> using namespace std; int main(){ // Providing a seed value srand((unsigned) time(NULL)); // A for loop to iterate code five 5 times for(int num=1; num<=5; num++){ //Range is given from 1 to 10 int random = 1 + (rand() % 10); // Display 5 int random numbers on screen cout <<"Random Number " <<num <<"= "<<random<<endl; } return 1; }
A sample output:
What is srand function?
- Is defined in the cstdlib header file.
- This function seeds the pseudo-random generator.
- It is used by the rand() function.
- The srand() function does not return any value.