fork download
  1. //Timothy Price CS1A Ch 6 challenge 8
  2. /*******************************************************************************
  3.  * Simulate coin toss
  4.  *
  5.  * This program receives a number and simulates that number of coin tosses.
  6.  *
  7.  * Inputs:
  8.  * number of coin tosses
  9.  *
  10.  * Outputs:
  11.  * coin tosses and results
  12. *******************************************************************************/
  13.  
  14. #include <iostream>
  15. #include <cstdlib> // Required for rand() and srand()
  16. #include <ctime> // Required for time()
  17.  
  18. using namespace std;
  19.  
  20. // Function to simulate a single coin toss
  21. void coinToss() {
  22. int toss_result = (rand() % 2) + 1;
  23.  
  24. if (toss_result == 1) {
  25. cout << " Heads" << endl;
  26. } else {
  27. cout << " Tails" << endl;
  28. }
  29. }
  30.  
  31. int main() {
  32. /*Seed the random number generator using the current system time.This
  33.   ensures you get a new sequence of flips every time you run the program*/
  34.  
  35. srand(time(0));
  36.  
  37. int total_toss = 0;
  38.  
  39. cout << "How many times should the coin be tossed? ";
  40. cin >> total_toss;
  41.  
  42. // Input validation
  43. if (total_toss <= 0) {
  44. cout << "Invalid input. Please enter a whole number greater than 0.";
  45. cout << endl;
  46. }
  47. if (total_toss > 0) {
  48. cout << total_toss << " tosses." << endl;
  49. cout << "Simulating coin tosses:" << endl;
  50. cout << "_______________________" << endl;
  51.  
  52. // Loop to run the coin toss simulation the exact number of times requested
  53. for (int flip_count = 0; flip_count < total_toss; ++flip_count) {
  54. coinToss();
  55. }
  56. }
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 5320KB
stdin
3
stdout
How many times should the coin be tossed? 3 tosses.
Simulating coin tosses:
_______________________
 Tails
 Heads
 Heads