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