Random
Published Aug 3, 2021Updated Mar 27, 2023
Contribute to Docs
C++ has a std::rand()
function from cstdlib
library that generates a random number.
For example, if we add #include <cstdlib>
, we can use the std::rand()
function:
std::cout << std::rand() << "\n";std::cout << std::rand() << "\n";std::cout << std::rand() << "\n";
It would output something like:
18042893838469308861681692777
Using Modulo
A lot of the times, we don’t just want any random number. Suppose We want a random number from 0-9.
int answer = std::rand() % 10;
The %
is the modulo symbol that returns the remainder.
Seeding the Random Number Generator
For our program to work, we need to get a different random number for each execution.
To do so, we need to add this line of code before the declaration of answer:
srand(time(NULL));
This sets the “seed” of the random number generator.
Codebyte Example
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours