// Vanessa Ramirez CSC5 Chapter 6, P. 371, #8
//
/*******************************************************************************
* COIN TOSS
* _____________________________________________________________________________
* This program stimulates tossing a coin by using the function coinToss.
* When the program calls the function it will randomly generate heads or tails
* and display the result each time the coin is tossed.
* _____________________________________________________________________________
* INPUT
* tosses - Number of times to toss the coin
*
* OUTPUT
* result - Head or tails of each toss
******************************************************************************/
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Function prototype
void coinToss();
int main()
{
// Declare program variables
int tosses;
int count;
// Initialize random number generator
srand(time(0));
// Get number of coin tosses
cout << "How many times should the coin be tossed? ";
cin >> tosses;
// Validate input
while (tosses < 1)
{
cout << "Please enter a number greater than 0: ";
cin >> tosses;
}
// Simulate the coin tosses
for (count = 1; count <= tosses; count++)
{
cout << "Toss " << count << ": ";
coinToss();
}
return 0;
}
// coinToss
// Generates a random number from 1 through 2.
// Displays head if the number is 1, or tails if it is 2.
//******************************************************************************
void coinToss()
{
int number;
// Generate a random number from 1 through 2
number = rand() % 2 + 1;
// Display the result
if (number == 1)
{
cout << "Heads" << endl;
}
else
{
cout << "Tails" << endl;
}
}