fork download
  1. //Charlotte Davies-Kiernan CS1A Chapter 6 P. 371 #8
  2. //
  3. /******************************************************************************
  4.  *
  5.  * Display Coin Toss Simulator
  6.  * ____________________________________________________________________________
  7.  * This program will display a coin toss simulator that displays the tossing
  8.  * of a coin the amount of times that is inputted and displays randomly,
  9.  * either heads or tails.
  10.  * ____________________________________________________________________________
  11.  * Input
  12.  * tosses //The amount of times the coin will be tossed
  13.  * Output
  14.  * result //The result of the toss, either heads or tails
  15.  *****************************************************************************/
  16. #include <iostream>
  17. #include <iomanip>
  18. #include <cstdlib>
  19. #include <ctime>
  20. using namespace std;
  21. //Function Prototype
  22. void coinToss ();
  23.  
  24. int main() {
  25. //Data Dictionary
  26. int tosses; //INPUT - The amount of times the coin will be tossed
  27. int result; //OUTPUT - The result of the toss, either heads or tails
  28. //Random Number Generator
  29. srand(time(0));
  30.  
  31. cout << "Coint Toss Simulator: " << endl;
  32. cout << "How many times should the coin be tossed? " << endl;
  33. cin >> tosses;
  34. if (tosses < 1){
  35. cout << "Invalid input. Please enter a positive integer: " << endl;
  36. cin >> tosses;
  37. }
  38. cout << "Tossing the coin " << tosses << " times..." << endl;
  39.  
  40. //Simulate coin tosses
  41. for (int i = 1; i <= tosses; i++){
  42. cout << "Toss " << i << ": ";
  43. coinToss();
  44. }
  45. cout << "Simulation complete!" << endl;
  46. return 0;
  47. }
  48. //Coin Toss Function
  49. void coinToss (){
  50. int result = rand() % 2 + 1;
  51. if (result == 1)
  52. cout << "Heads" << endl;
  53. else
  54. cout << "Tails" << endl;
  55. }
Success #stdin #stdout 0.01s 5320KB
stdin
4
stdout
Coint Toss Simulator: 
How many times should the coin be tossed? 
Tossing the coin 4 times...
Toss 1: Tails
Toss 2: Heads
Toss 3: Tails
Toss 4: Heads
Simulation complete!