← Back to Week 2 Hub

Roll the Dice

Create a Dice class and simulate 100 rolls, tracking specific sums

Workbook 2a, p.64-65 — Exercise 2

What You're Building

Create a Dice class with a roll() method that returns a random number from 1 to 6. In your main program, create two Dice objects and roll them both 100 times. Each roll, print the two values and their sum. Keep counters for how many times the sum equals 2, 4, 6, or 7. After all 100 rolls, display the final counts.

Example Run

Sample Output (showing first few and last few of 100 rolls)

Roll 1: 4 - 6 Sum: 10 Roll 2: 1 - 1 Sum: 2 *** Roll 3: 3 - 4 Sum: 7 *** Roll 4: 5 - 2 Sum: 7 *** Roll 5: 2 - 2 Sum: 4 *** Roll 6: 6 - 3 Sum: 9 ... Roll 98: 3 - 3 Sum: 6 *** Roll 99: 1 - 5 Sum: 6 *** Roll100: 4 - 4 Sum: 8 Number of 2s: 3 Number of 4s: 8 Number of 6s: 14 Number of 7s: 17

The *** marks indicate rolls where the sum matched one of the tracked values (2, 4, 6, or 7). Your numbers will differ each run since dice are random.

Key detail: The Dice class is its own file with one job — generate a random value from 1 to 6 when roll() is called. The main program creates objects from it and handles the looping and counting.
Concepts You'll Use

This exercise reinforces these concepts from Week 2:

Flow Diagram
Step 1 Create Dice class With roll() method
Step 2 In main: create 2 dice Plus 4 counters (2,4,6,7)
Loop 100x Roll both dice Print values + sum
Inside Loop Check the sum If 2, 4, 6, or 7: increment
After Loop Display counters How many 2s, 4s, 6s, 7s

Each run will produce different results because dice rolls are random. That's expected.

← Looping Exercises Test Statistics →