VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-generate-random-value-by-dice-roll-in-cpp/

⇱ How to Generate Random Value by Dice Roll in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Generate Random Value by Dice Roll in C++?

Last Updated : 23 Jul, 2025

In C++, we can simulate a dice roll by generating random numbers within a specific range. In this article, we will learn how to generate random values by dice roll in C++.

Example:

Input: 
Roll a dice

Output:
Dice roll result is: 4

Generating Random Values Similar to a Dice Roll

To simulate a dice roll, we can use the <random> library in C++. We will generate a random number between 1 and 6 (inclusive), which corresponds to the possible outcomes of a six-sided dice roll.

Approach:

  • Define a range (here to 1 to 6 inclusive).
  • Seed an mt19937 object gen with the time-generated seed.
  • Now, create a uniform_int_distribution<> object distrib. This models a random number generator that produces uniformly distributed integers within a specified range. Pass the minimum and maximum values of the range as parameters.
  • Call the distributor by passing the generator as a parameter to get a generate a random number in a range.
  • Finally, print the generated random number.

C++ Program to Generate Random Values by Dice Roll 

The below program demonstrates how we can simulate a dice roll in C++.


Output
 Dice roll result is: 2

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags: