In: Computer Science
Write a program that determines the probability of tossing a coin 10 times and getting exactly 0, 1, 2, 3, etc. heads. This is the binomial probability distribution. Store the probability in an array. You could get 0 heads or 10 heads or anything inbetween.
Use a for loop. The for loop will go from 0 to 10 inclusive. Use r as the number of successes. So r will go from 0 to 10. The probability of a success is .5, and also the probability of a failure is .5.
Print out in table form, column 1=r; goes 0 to 10, and then column 2; the probability of r.
Use 4 decimal places for the probability. You know if you get the correct answers because The sum of all the probabilities is 1.0, and all probabilities are in the range of 0 to 1 inclusive.
In C++, prefer visual studios but not required.
The code is as follows:
#include <iostream>
#include<cmath>
#include <sstream>
#include <iomanip>
using namespace std;
// Returns factorial of n
int fact (int n)
{
int s = 1;
for (int i = 2; i <= n; i++)
    s = s * i;
return s;
}
int nCr (int n, int r)
{
return fact (n) / (fact (r) * fact (n - r));
}
int main ()
{
double prob[11][2];       //array to store
the probability values
double p = 0.5;       //probability of
pass
double f = 0.5;       //probability of
failure
double x = 0;
int n = 10;          
//number of tries
for (int i = 0; i <= 10; i++)
    {
      x = nCr (n, i) * pow (p, i) * pow
(f, n - i); // The formula is used to calculate the
probability
      //following three lines of code is
used for rounding the value to 4 decimal places
      stringstream tmp;
      tmp << setprecision(4)
<< fixed << x;
      double new_val =
stod(tmp.str());
      prob[i][0] = i;
      prob[i][1] = new_val;
    }
cout << "The probability of tossing a coin 10 times and
getting exactly 0, 1, 2, ... ,10 heads is as follows:
"    << endl;
for (int j = 0; j <= 10; j++)
    {
        cout << "X = "
<< prob[j][0] << "   P = " <<
prob[j][1] << endl;
    }
return 0;
}