
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to generate a random number in C++?
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 pseudorandom 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
#include<iostream> #include<cstdlib> #include<ctime> 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; }
Output1
The random number is: 51
Output 2
The random number is: 29
Output 3
The random number is: 47
- Related Articles
- How to generate a random number in JavaScript?
- C++ program to generate random number
- How to generate 6-digit random number in MySQL?
- How to generate different random numbers in a loop in C++?
- How can I generate random number in a given range in Android?
- Generate Random Float type number in Java
- Generate Random double type number in Java
- How do I generate random floats in C++?
- C++ Program to Generate a Random UnDirected Graph for a Given Number of Edges
- C++ program to generate random alphabets
- Generate Random Point in a Circle in C++
- Java Program to generate a random number from an array
- Java Program to generate random number with restrictions
- How to generate a random BigInteger value in Java?
- How to generate random colors in Matplotlib?
