//Timothy Price CS1A Ch 6 challenge 8
/*******************************************************************************
* Simulate coin toss
*
* This program receives a number and simulates that number of coin tosses.
*
* Inputs:
* number of coin tosses
*
* Outputs:
* coin tosses and results
*******************************************************************************/
#include <iostream>
#include <cstdlib> // Required for rand() and srand()
#include <ctime> // Required for time()
using namespace std;
// Function to simulate a single coin toss
void coinToss() {
int toss_result = (rand() % 2) + 1;
if (toss_result == 1) {
cout << " Heads" << endl;
} else {
cout << " Tails" << endl;
}
}
int main() {
/*Seed the random number generator using the current system time.This
ensures you get a new sequence of flips every time you run the program*/
srand(time(0));
int total_toss = 0;
cout << "How many times should the coin be tossed? ";
cin >> total_toss;
// Input validation
if (total_toss <= 0) {
cout << "Invalid input. Please enter a whole number greater than 0.";
cout << endl;
}
if (total_toss > 0) {
cout << total_toss << " tosses." << endl;
cout << "Simulating coin tosses:" << endl;
cout << "_______________________" << endl;
// Loop to run the coin toss simulation the exact number of times requested
for (int flip_count = 0; flip_count < total_toss; ++flip_count) {
coinToss();
}
}
return 0;
}