fork download
  1. // Vanessa Ramirez CSC5 Chapter 6, P. 371, #8
  2. //
  3. /*******************************************************************************
  4.  * COIN TOSS
  5.  * _____________________________________________________________________________
  6.  * This program stimulates tossing a coin by using the function coinToss.
  7.  * When the program calls the function it will randomly generate heads or tails
  8.  * and display the result each time the coin is tossed.
  9.  * _____________________________________________________________________________
  10.  * INPUT
  11.  * tosses - Number of times to toss the coin
  12.  *
  13.  * OUTPUT
  14.  * result - Head or tails of each toss
  15.  ******************************************************************************/
  16. #include <iostream>
  17. #include <cstdlib>
  18. #include <ctime>
  19. using namespace std;
  20.  
  21. // Function prototype
  22. void coinToss();
  23.  
  24. int main()
  25. {
  26. // Declare program variables
  27. int tosses;
  28. int count;
  29.  
  30. // Initialize random number generator
  31. srand(time(0));
  32.  
  33. // Get number of coin tosses
  34. cout << "How many times should the coin be tossed? ";
  35. cin >> tosses;
  36.  
  37. // Validate input
  38. while (tosses < 1)
  39. {
  40. cout << "Please enter a number greater than 0: ";
  41. cin >> tosses;
  42. }
  43.  
  44. // Simulate the coin tosses
  45. for (count = 1; count <= tosses; count++)
  46. {
  47. cout << "Toss " << count << ": ";
  48. coinToss();
  49. }
  50.  
  51. return 0;
  52. }
  53.  
  54. // coinToss
  55. // Generates a random number from 1 through 2.
  56. // Displays head if the number is 1, or tails if it is 2.
  57. //******************************************************************************
  58. void coinToss()
  59. {
  60. int number;
  61.  
  62. // Generate a random number from 1 through 2
  63. number = rand() % 2 + 1;
  64.  
  65. // Display the result
  66. if (number == 1)
  67. {
  68. cout << "Heads" << endl;
  69. }
  70. else
  71. {
  72. cout << "Tails" << endl;
  73. }
  74. }
Success #stdin #stdout 0s 5316KB
stdin
5
stdout
How many times should the coin be tossed? Toss 1: Tails
Toss 2: Heads
Toss 3: Tails
Toss 4: Tails
Toss 5: Tails