Tuesday, January 3, 2017

Programming Challenge 6.8 - Coin Toss

/* Coin Toss - This program uses the function:

* coinToss()

It is demonstrated by calling the function in this program which
asks the user how many many times the coin should be tossed and
then simluates the tossing of the coin that number of times. */

#include "Utility.h"

/* Prototype: Coin Toss */
void coinToss(int);

int main()
{
   /* Variable: Throw Coin */
   int numTosses = 0;

   /* Display: Introduction
      Get: The number of coin tosses from the user
      Call: coinToss */
   cout << "\t\tCoin Toss Simulator\n\n"
        << "Deciding between two things isn't always easy.\n"
        << "Cake or Cabbage? Right or Left? New Clothes or\n"
        << "Second Hand? Which shall it be?\n"
        << "This program is the ideal solution to this very\n"
        << "problem! Simply enter the number of times a coin\n"
        << "should be tossed, and let the outcome decide.\n\n"
        << "How many times should the coin be tossed? ";
   cin >> numTosses;

   /* Input Validation: If the input is 0 or negative, the user
      gets a message to try again */
   while (numTosses <= 0)
   {
      cout << "It seems that you entered 0 or a negative\n"
           << "number which is invalid. Please try again.\n"
           << "How many times should the coin be tossed? ";
      cin >> numTosses;
   }

   coinToss(numTosses);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: coinToss

   This function accepts a number it gets from user input as
   argument, and generates a random number in the range of 1
   through 2.

   * If the random number is 1, "heads" is displayed.
   * If the random number is 2, "tails" is displayed.
   ********************************************************** */

void coinToss(int coinTosses)
{
   /* Constants: Heads, Tails */
   const int HEADS = 1,
             TAILS = 2;

   /* Variable: randomThrow */
   int randomThrow = 0;

   /* Set: Seed of the random number generator*/
   srand((unsigned int)time(NULL));

   /* Display: Table Header */
   cout << "\nThrow No: " << "\tWas: ";
   cout << "\n---------------------\n";

   /* While this loop iterates, randomThrow will produce random
      numbers, the conditional statement determines whether the
      throw was heads or tails, and the result is displayed */
   for (int throws = 1; throws <= coinTosses; throws++)
   {
      randomThrow = (rand() % (TAILS - HEADS + 1)) + HEADS;

      randomThrow == HEADS ? cout << throws << "\t\tHeads\n" :
                             cout << throws << "\t\tTails\n";
   }
}

No comments:

Post a Comment