Coin Flip Simulation Program in C++
Posted by Samath
Last Updated: January 07, 2021
  14045

Write a program that simulates 10-flips of a coin. Write a function names coinToss that simulates the tossing of a coin. When you call the function, it should generate a random number in the range 1 through 2. If the random number is 1, the function should display “Head”, otherwise, “Tails”. 

Every time head comes up, the player wins $1; every time tail comes up, the player loses $1. Write another function named calculateTotal that adds up the player’s winnings after 10 flips of the coin. Your program should produce random results. 

Output:

Code:

#include <string>
#include <time.h>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <windows.h>
 
using namespace std;
int coinToss();
float calculateTotal(int number, float money);
 
int main(int argv, char argc[])
{
   int number;
   float money = 0;
   int head = 0;
   int tail = 0;
   
   cout<<"\t\tMy Coin Flip Simulation Program"<<endl;
   
 
   for(int i = 0; i < 10; i++)
   {
      number = coinToss();
      if(number == 1)
      {
        cout<<"HEADS"<<endl;  
        money = calculateTotal(number,money); 
        head ++;    
      }
      else
      {
         cout<<"TAILS"<<endl; 
         money = calculateTotal(number,money);  
         tail ++;
      }
       Sleep(1000);
   }
   
   cout<<"Total heads: "<<head<<endl;
   cout<<"Total tails: "<<tail<<endl;
   cout<<"Total winnings: $"<<money<<endl;
 
    system("pause");
    return 0;
}
 
float calculateTotal(int number, float money)
{
    if(number == 1)
      {
        money = money + 1.0;      
      }
      else
      {
          money = money - 1.0;  
      }
    return money;
}
 
int coinToss()
{
    int num;   
    
 
    srand ((unsigned) time(0));
    num = rand()%2 + 1;  
  
   
    
    return num;
}