Write a random number generator that generates random numbers between 1 and 6 (simulates a dice) program in Python C and Java

“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.

🎲 Dice Simulator: Random Numbers from 1 to 6

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

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.

LanguageDice statementWhat it gives
Pythonrandom.randint(1, 6)A whole number from 1 to 6, both included
Crand() % 6 + 1rand() % 6 is 0 to 5, and + 1 makes it 1 to 6
Javarnd.nextInt(6) + 1nextInt(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 betweenr × 6 is betweenAfter floorDice shows
0 and 0.16660 and 101
0.1667 and 0.33331 and 212
0.3334 and 0.52 and 323
0.5001 and 0.66663 and 434
0.6667 and 0.83334 and 545
0.8334 and 0.99995 and 656

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 n times with a for loop.
  • 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 = 0 and count = 0.
  • While d is not 6, roll the dice, add 1 to count and 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.

irr × 6floord = floor + 1Printed
00.08300.498001You rolled: 1
10.45002.700023You rolled: 3
20.91005.460056You 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() % 6 gives 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 6 on 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 of main().
  • Typing text for n: int(input()) stops with ValueError: invalid literal for int() with base 10: 'abc'. Enter a whole number.
  • Java class name: if the class is Dice, the file must be Dice.java.

Practice Questions

  1. Roll two dice and print their sum.
  2. Roll the dice 60 times and count how many times each face appears.
  3. Roll two dice until both show the same number (a double).
  4. Make a game: the user guesses a number from 1 to 6 and the program tells whether the guess matches the dice.
  5. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top