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).
Pro Tip: Why +1?
The expression rand() % 6 produces values from 0 to 5. We add 1 to shift the range to 1-6, matching a real-world die.
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
#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:
The number is even.