“Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)” is one of the most popular beginner programs in Python, C and Java. It teaches you how to use a library, how a program makes a random choice, and how a loop repeats it. In this post you will get three complete programs (roll once, roll many times and roll until a 6 comes) in all three languages, the idea of how a dice number is made from a random decimal, a dry run, common mistakes with real outputs, practice questions and an FAQ. Use the interactive dice below to see every step.
Roll a virtual dice and see how the computer turns a random number into a dice face.
Graphical view
Code
Output
What You Will Learn
- The problem statement
- How a computer rolls a dice
- The programs in Python, C and Java
- Dry run
- Other ways to get a random number
- Common mistakes, practice questions and FAQ
Problem Statement
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
A real dice has six faces, and every face has the same chance of coming up. The program must produce a whole number from 1 to 6 each time it runs, and every number must be equally likely. In this post we write the program in three forms: roll the dice once, roll it n times with a for loop, and keep rolling with a while loop until a 6 comes. The interactive tool above lets you choose any of the three.
How a Computer Rolls a Dice
A computer cannot throw a dice, so it uses a random number generator. It is a formula that produces numbers that look random and are evenly spread. Every language gives you a ready-made function for it, and you only have to turn its result into the range 1 to 6.
| Language | Dice statement | What it gives |
|---|---|---|
| Python | random.randint(1, 6) | A whole number from 1 to 6, both included |
| C | rand() % 6 + 1 | rand() % 6 is 0 to 5, and + 1 makes it 1 to 6 |
| Java | rnd.nextInt(6) + 1 | nextInt(6) is 0 to 5, and + 1 makes it 1 to 6 |
To understand the idea behind these statements, picture a random decimal r from 0 up to 1 (1 itself is never reached). Cut the line from 0 to 1 into six equal parts. The part in which r lands decides the dice face. In four steps:
- Step 1: pick a random decimal r, for example 0.7152.
- Step 2: multiply by 6: 0.7152 × 6 = 4.2912.
- Step 3: drop the decimal part: 4. The result is always 0, 1, 2, 3, 4 or 5.
- Step 4: add 1: 4 + 1 = 5. The dice shows 5.
| r is between | r × 6 is between | After floor | Dice shows |
|---|---|---|---|
| 0 and 0.1666 | 0 and 1 | 0 | 1 |
| 0.1667 and 0.3333 | 1 and 2 | 1 | 2 |
| 0.3334 and 0.5 | 2 and 3 | 2 | 3 |
| 0.5001 and 0.6666 | 3 and 4 | 3 | 4 |
| 0.6667 and 0.8333 | 4 and 5 | 4 | 5 |
| 0.8334 and 0.9999 | 5 and 6 | 5 | 6 |
Because the six parts have the same size, every face has the same chance. We tested this with Python by rolling 60,000 times. Every face came up about 10,000 times (between 9,870 and 10,201), which is what a fair dice should do.
One more point: these numbers are pseudo-random. They start from a number called the seed. The same seed gives the same sequence, so C and Java programs seed the generator from the current time to get a different sequence every run. Python does this by itself.
The Programs
Program 1: Roll the dice once
Logic: get one random number from 1 to 6, store it in d and print it.
Python
import random
d = random.randint(1, 6)
print("You rolled:", d)
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned)time(NULL));
int d = rand() % 6 + 1;
printf("You rolled: %d\n", d);
return 0;
}
Java (save as Dice.java)
import java.util.Random;
public class Dice {
public static void main(String[] args) {
Random rnd = new Random();
int d = rnd.nextInt(6) + 1;
System.out.println("You rolled: " + d);
}
}
Sample output (yours will be different every time):
You rolled: 2
Program 2: Roll the dice n times
Logic:
- Ask the user for
n, the number of rolls. - Repeat
ntimes with aforloop. - In every turn, get a random number from 1 to 6 and print it.
Python
import random
n = int(input("How many times to roll the dice? "))
for i in range(n):
d = random.randint(1, 6)
print("You rolled:", d)
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned)time(NULL));
int n;
printf("How many times to roll the dice? ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int d = rand() % 6 + 1;
printf("You rolled: %d\n", d);
}
return 0;
}
Java (save as Dice.java)
import java.util.Random;
import java.util.Scanner;
public class Dice {
public static void main(String[] args) {
Random rnd = new Random();
Scanner sc = new Scanner(System.in);
System.out.print("How many times to roll the dice? ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int d = rnd.nextInt(6) + 1;
System.out.println("You rolled: " + d);
}
}
}
Sample output (the user typed 5, the numbers change on every run):
How many times to roll the dice? 5
You rolled: 6
You rolled: 1
You rolled: 1
You rolled: 1
You rolled: 1
Program 3: Roll until a 6 comes
Logic:
- Set
d = 0andcount = 0. - While
dis not 6, roll the dice, add 1 tocountand print the number. - When 6 comes, the condition becomes false and the loop stops. Print how many rolls it took.
Python
import random
count = 0
d = 0
while d != 6:
d = random.randint(1, 6)
count += 1
print("You rolled:", d)
print("Got a 6 after", count, "rolls")
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned)time(NULL));
int d = 0, count = 0;
while (d != 6) {
d = rand() % 6 + 1;
count++;
printf("You rolled: %d\n", d);
}
printf("Got a 6 after %d rolls\n", count);
return 0;
}
Java (save as Dice.java)
import java.util.Random;
public class Dice {
public static void main(String[] args) {
Random rnd = new Random();
int d = 0, count = 0;
while (d != 6) {
d = rnd.nextInt(6) + 1;
count++;
System.out.println("You rolled: " + d);
}
System.out.println("Got a 6 after " + count + " rolls");
}
}
Sample output (the number of rolls is different every time):
You rolled: 1
You rolled: 2
You rolled: 2
You rolled: 2
You rolled: 1
You rolled: 2
You rolled: 6
Got a 6 after 7 rolls
On average a 6 needs about 6 rolls, but it can come on the very first roll or take many more. Our Java test run needed 17 rolls.
Dry Run
Take Program 2 with n = 3. Suppose the generator picks these decimals: 0.0830, 0.4500 and 0.9100.
| i | r | r × 6 | floor | d = floor + 1 | Printed |
|---|---|---|---|---|---|
| 0 | 0.0830 | 0.4980 | 0 | 1 | You rolled: 1 |
| 1 | 0.4500 | 2.7000 | 2 | 3 | You rolled: 3 |
| 2 | 0.9100 | 5.4600 | 5 | 6 | You rolled: 6 |
In a real run you cannot see r, but the interactive tool shows it for every roll. In Program 3, the same table continues row by row until d becomes 6, and then the loop stops.
Other Ways to Get a Random Number
Python: these four lines all give a number from 1 to 6. We ran each of them 5,000 times and saw exactly the numbers 1 to 6.
import random
a = random.randint(1, 6)
b = random.randrange(1, 7)
c = random.choice([1, 2, 3, 4, 5, 6])
d = int(random.random() * 6) + 1
Java: two more ways. The first follows the four steps of this post exactly. The second gives a number in the range 1 to 6 directly (the upper limit 7 is not included).
int a = (int) (Math.random() * 6) + 1;
int b = ThreadLocalRandom.current().nextInt(1, 7);Needs import java.util.concurrent.ThreadLocalRandom; at the top.
Same numbers every time (testing): set a seed. In Python the two runs below print the same list, which we confirmed.
import random
random.seed(42)
print([random.randint(1, 6) for _ in range(5)])[6, 1, 1, 6, 3]Remove random.seed(42) when you want a real random game.
Common Mistakes
- Using randint(0, 6): this gives 0 to 6, which is seven values. We saw 0 within 5,000 tries. Use
randint(1, 6). - Using randrange(1, 6): the end value is excluded, so 6 never comes. We got only 1 to 5 in 5,000 tries. Use
randrange(1, 7). - Forgetting + 1 in C or Java:
rand() % 6gives 0 to 5. In 5,000 tries the value 6 appeared 0 times and the value 0 appeared about 800 times. - Forgetting srand() in C: the program prints the same numbers every run. We ran it twice and both runs printed
2 5 4 2 6on our test machine. - Calling srand() inside the loop: if you reseed in every turn with
time(NULL), all the rolls in the same second are equal. Call it once at the start ofmain(). - Typing text for n:
int(input())stops withValueError: invalid literal for int() with base 10: 'abc'. Enter a whole number. - Java class name: if the class is
Dice, the file must beDice.java.
Practice Questions
- Roll two dice and print their sum.
- Roll the dice 60 times and count how many times each face appears.
- Roll two dice until both show the same number (a double).
- Make a game: the user guesses a number from 1 to 6 and the program tells whether the guess matches the dice.
- Write a program that rolls a dice 1000 times and prints the average.
Frequently Asked Questions
How do you generate a random number between 1 and 6 in Python?
Import the random module and call random.randint(1, 6). Both 1 and 6 are included, so it behaves exactly like a dice. random.randrange(1, 7) and random.choice([1, 2, 3, 4, 5, 6]) give the same kind of result.
Why does C use rand() % 6 + 1?
rand() returns a large whole number. % 6 keeps only the remainder after dividing by 6, which is 0, 1, 2, 3, 4 or 5. Adding 1 shifts this range to 1 to 6. Without the + 1 the program can print 0 and never print 6.
Why do I get the same dice numbers every time I run my C program?
Because the generator was not seeded. Without srand(), rand() starts from the same value each run and produces the same sequence. Call srand((unsigned)time(NULL)); once at the start of main(). The current time is different each second, so the sequence is different.
Are computer random numbers really random?
They are pseudo-random. A formula produces numbers that look random and are evenly spread, but they start from a seed. The same seed gives the same sequence. For a dice game or a class practical this is perfectly fine.
How does random.randint(1, 6) work?
It picks a whole number from 1 to 6, and every number has the same chance. A simple way to picture it is: take a random decimal r from 0 up to 1, multiply by 6, drop the decimal part to get 0 to 5, and add 1. The interactive tool above shows these four steps.
What is the difference between randint(1, 6) and randrange(1, 6)?
randint(a, b) includes both ends. randrange(1, 6) works like range() and stops before 6, so it only gives 1 to 5. For a dice use randrange(1, 7) or randint(1, 6).
How do I roll the dice a number of times?
Put the roll inside a loop. In Python use for i in range(n): and call random.randint(1, 6) in every turn, as in Program 2 above.
How do I keep rolling until a 6 comes?
Use a while loop. Start with d = 0, run while d != 6:, roll the dice inside the loop and count the rolls. The loop stops when 6 appears. This is Program 3 above.
How can I get the same random numbers again for testing?
Set a seed first. In Python, random.seed(42) before the rolls always gives the same list. In Java use new Random(42). In C use srand(42). Remove the fixed seed for the real game.
Which is better in Java: Random.nextInt(6) + 1 or Math.random() * 6?
Both work. rnd.nextInt(6) + 1 is shorter and gives a whole number directly. (int) (Math.random() * 6) + 1 does the same job in the style of the four steps in this post. ThreadLocalRandom.current().nextInt(1, 7) is another option.