# Gillius's Programming Forums

## Hosted Forum: West Visayas State University - Philippines => Problem Solving and Programming Class Forum => Topic started by: louiecerv on January 23, 2006, 12:31:33 AM

Title: COIN FLIPPING - Using functions for subtasks
Post by: louiecerv on January 23, 2006, 12:31:33 AM
If you toss a coin two times, should you expect to get one head and one tail? If you toss the same coin ten times should you expect to get five heads and five tails?
To investigate this problem, write a program that will simulate the tossing of a coin N times (N must be even) and count the number of heads and tails. Repeat this experiment R times and summarize the results as shown below.  The user should be able to repeat the program with new data.

Test your program for N=4 , R=10 and N=10, R=20

Sample Run
Number of tosses (Even)? 4
Number of repetitions? 10
H     T
HTTT    1   3
THHH    3   1
HTTT    1   3
THTT    1   3
TTTT    0   4
TTHH    2    2 EQUAL
HTTH    2   2 EQUAL
HTTT    1   3
TTHH    2   2 EQUAL
HHHH    4   0
Heads=Tails 3 out of 10 times.

NOTE: The result you get will vary because the random number function will produce different sets of random numbers

HINT:

Add the following include directives to access random function rand():
#include <cstdlib>
#include <ctime>
include <iomanip>   //required by the setw() command

Create and call the following function in the main program to generate random heads and tails:

char ThrowCoin()
{
if ( rand() > (RAND_MAX/2) )
return 'H';
else
return 'T';
}
Title: A solution to the Coin Flipping Problem
Post by: louiecerv on January 23, 2006, 12:33:35 AM
Code: [Select]
`#include <iostream>#include <cmath>#include <cstdlib>#include <ctime>#include <iomanip>using namespace std;char ThrowCoin();int main(){    // initialize ramdom with time    // to improve 'randomness'    srand ( time(NULL) );        int N, R;        do     {        cout << "\nNumber of tosses (even)?  ";        cin >> N;        cout << "Number of repetitions?    ";        cin >> R;        int h_equals_t=0;        cout << endl;        cout << setw(N+4)<< "H" << setw(5) << "T\n";                   for (int i = 0; i<R; i++)        {                   int heads=0, tails = 0;             for (int j = 0; j<N;j++)            {                char result = ThrowCoin();                if (result=='H')                    heads++;                else                    tails++;                cout << result;                }            cout << setw(4) << heads << setw(4) << tails;            if (heads == tails)            {                h_equals_t++;                cout << " equal";            }               cout << endl;        }        cout << "Heads=Tails " << h_equals_t              << " out of " << R << " times.\n";    } while (1==1);       system("PAUSE");    return 0;}char ThrowCoin(){    if ( rand() > (RAND_MAX/2) )        return 'H';    else        return 'T';}`