        
// find the probability it takes 5 tosses of a fair coin to get 2 heads 


#include <stdlib.h>  // needed for RAND_MAX 

#define NREPS 100000  // number of times we will repeat the experiment 

int N5 = 0,  // number of times T = 5 
    X;  // number of heads

float P; // probability of heads

/* the function Rnd(Prob) simulates a random event of probability
   Prob, with the return value 1 meaning the event occurred and 0
   meaning that it did not occur */

int Rnd(float Prob)

{  return((rand() < Prob * RAND_MAX));  }

DoExperiment()

{  int NHeads=0;

   for (X = 1; ; X++)  {
      if (Rnd(0.5))  {
         NHeads++;
         if (NHeads == 3) break;
      }
   }
}

UpdateCounts()

{  if (X == 5) N5++;
}

PrintResults()

{  printf("P(X = 5) = %f\n",((float) N5)/NREPS);
}

main(argc,argv)
   int argc; char **argv;

{  int I;

   for (I = 0; I < NREPS; I++)  {
      DoExperiment();
      UpdateCounts();
   }

   PrintResults();
}

