2 C++ Programs to Generate Random Numbers Between 1 to 10

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:

-CPP-random-1-10

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:

CPP-random-1-10

What is srand function?

The srand() function is:

  • 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
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!