Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++: Write a function named BinaryFlip that simulates the tossing of a coin.

ID: 3803782 • Letter: I

Question

In C++:

Write a function named BinaryFlip that simulates the tossing of a coin. When you call the function, it should generate a random number either 0 or 1. If the random number is 0, the function should display “Heads.” If the random number is 1, the function should display “Tails.”

1. Demonstrate the function in a program that asks the user how many times the coin should be tossed, and then simulates the tossing of the coin that number of times, and prints the outcome each time when the coin is tossed.

2. Print the probability of getting Head and Tail, following each toss.

Example Output: Enter the number of tosses:

20

1 Heads P(H) = 1 P(T) = 0

2 Tails P(H) = 0.5 P(T) = 0.5

.

.

.

20 Tails P(H) = 0.71 P(T) = 0.29

Note: Use Static/Global variables

Hint: To generate either 0 or 1 randomly, use

double fraction = ((double) rand() / (RAND_MAX))

if fraction is >= 0.5 consider the outcome as “1”, otherwise “0”

Explanation / Answer

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int coinFlip(int flipFunc);      
int main()
{
int tosses, count;  
count = 0;
cout << "How many tosses should I make?" << endl;      
cin >> tosses;
while (count <= tosses)
{
cout << coinFlip << endl;
count++;      
}
system("pause");
return 0;                  
}
int coinFlip(int flipFunc)  
{  
unsigned seed = time(0);
srand (seed);          
int flip = 1 + rand() % 2;  
if (flip == 1)
{
cout << "Heads!. ";
}
else if (flip == 2)
{
cout << "Tails!. ";
}
return flip;
}