Dice Roll Simulator: Random Number Generation and Even-Odd Logic

C++ Program: Dice Roll Simulation and Even-Odd Logic

In this C++ exercise, you will create a program that simulates the roll of a standard six-sided die. The result of the roll is randomly generated using the C++ random number facilities. After generating the number, the program will determine whether the outcome is even or odd and display a corresponding message.

This program is a great way to get hands-on experience with random number generation, conditional logic, and the modulus operator.

Core Concepts

Random Seeding

We use srand(time(0)) to ensure that every time you run the program, the sequence of numbers is different based on the current system time.

Modulus Operator (%)

Dividing by 2 and checking the remainder is the standard way to identify parity (Even: 0, Odd: 1).

Objectives

  • 1. Seed the random generator with ctime.
  • 2. Simulate a 6-sided die roll using rand() % 6 + 1.
  • 3. Evaluate parity using the modulus operator (%).
  • 4. Print formatted output based on the result.

Example C++ Code

dice_roll.cpp Source Code
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    // Seed the random number generator
    srand(time(0));

    // Generate random number between 1 and 6
    int dieRoll = rand() % 6 + 1;

    cout << "You rolled a " << dieRoll << "." << endl;

    // Parity check
    if (dieRoll % 2 == 0) {
        cout << "The number is even." << endl;
    } else {
        cout << "The number is odd." << endl;
    }

    return 0;
}

Console Output:

You rolled a 4.
The number is even.
Keywords & Concepts
srand() & rand() Modulus Operator (%) Even vs Odd ctime Library
© C++ Programming Exercises. Master the art of performance coding.