

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to generate random number
Let us see how to generate random numbers using C++. Here we are generating a random number in range 0 to some value. (In this program the max value is 100).
To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand.
The declaration of srand() is like below
void srand(unsigned int seed)
It takes a parameter called seed. This is an integer value to be used as seed by the pseudo-random number generator algorithm. This function returns nothing.
To get the number we need the rand() method. To get the number in range 0 to max, we are using modulus operator to get the remainder.
For the seed value we are providing the time(0) function result into the srand() function.
Example Code
#include<iostream> #include<cstdlib> #include using namespace std; main() { int max; max = 100; //set the upper bound to generate the random number srand(time(0)); cout << "The random number is: "<<rand()%max; }
Output 1
The random number is: 51
Output 2
The random number is: 29
Output 3
The random number is: 47
- Related Questions & Answers
- C++ program to generate random alphabets
- Java Program to generate random number with restrictions
- C# Program to generate random lowercase letter
- C# program to generate secure random numbers
- C++ Program to Generate Random Hexadecimal Bytes
- How to generate a random number in C++?
- Java Program to generate custom random number -1 or 1
- Java Program to generate a random number from an array
- Java program to generate random numbers
- C++ Program to Generate a Random UnDirected Graph for a Given Number of Edges
- Java Program to generate random numbers string
- How to generate a random number in JavaScript?
- C++ Program to Generate Random Numbers Using Middle Square Method
- C++ Program to Generate Random Numbers Using Probability Distribution Function
- C++ Program to Generate a Random Subset by Coin Flipping