
- 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 different random numbers in a loop in C++?
Let us see how to generate different random numbers using C++. Here we are generating random numbers 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
#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)); for(int i = 0; i<10; i++) { //generate 10 random numbers cout << "The random number is: "<<rand()%max << endl; } }
Output
The random number is: 6 The random number is: 82 The random number is: 51 The random number is: 46 The random number is: 97 The random number is: 60 The random number is: 20 The random number is: 2 The random number is: 55 The random number is: 91
- Related Articles
- How to generate large random numbers in Java?
- How to generate random numbers between two numbers in JavaScript?
- Generate random numbers in Arduino
- How to generate non-repeating random numbers in Python?
- How to generate standard normal random numbers in R?
- Guide to Generate Random Numbers in Linux
- How to generate random whole numbers in JavaScript in a specific range?
- Generate pseudo-random numbers in Python
- Generate Random Integer Numbers in Java
- How does Python generate random numbers?
- How to generate 5 random numbers in MySQL stored procedure?
- Java program to generate random numbers
- How to use Python Numpy to generate Random Numbers?
- PHP program different ways to generate a random string
- Generate Random Long type numbers in Java
