Dice Roll Simulation and Even-Odd Determination in C++

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 basic input/output operations in C++. It also helps reinforce the concepts of modulus operations and using standard libraries.

The die roll will generate a random number between 1 and 6, and the program will then evaluate whether the number is divisible by 2. Based on this check, it will output either "even" or "odd".

Group

Advanced Conditional Structures in C++

Objective

1. Use the random number generator to simulate the roll of a six-sided die.
2. Display the rolled number.
3. Determine whether the number is even or odd using the modulus operator.
4. Print a message indicating if the number is even or odd.

Create a program that simulates rolling a die and determines whether the number is even or odd.

Example C++ Exercise

 Copy C++ Code
#include <iostream>       // Include the input/output stream library
#include <cstdlib>        // Include the C standard library for rand() and srand()
#include <ctime>          // Include the C time library to seed the random number generator

using namespace std;

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

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

    // Display the result of the die roll
    cout << "You rolled a " << dieRoll << "." << endl;

    // Check if the number is even or odd
    if (dieRoll % 2 == 0) {
        // Output message for even number
        cout << "The number is even." << endl;
    } else {
        // Output message for odd number
        cout << "The number is odd." << endl;
    }

    return 0; // End of program
}

 Output

You rolled a 4.
The number is even.

Share this C++ Exercise


More C++ Programming Exercises of Advanced Conditional Structures in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.