CMIS 141
Heads or tails Lab
Make a program (either an application or an applet) that simulates
coin tosses. Let the user specify how many tosses to do. Count the
number of heads and tails. Use Math.random() Hint: if it's less than
.5 it's a head.
Report the number of heads and tails and the percentage that each is
of the number of tosses (should be close to 50% each). Remember to do
real division.
Run the program several times with these number of flips:
#Flips %heads %tails
------ --------- ---------
100
100
100
1000
1000
1000
1000000
1000000
1000000
10000000
10000000
10000000
What trend do you see about the percentages as the number of coin
flips increases?
*************************************
Harder:
during the tossings find the largest difference between the number of
heads and the number of tails, i.e. where the number of heads is the
most more than the number of tails. This is a find the maximum
problem, so a max variable is needed and each time there is a new max
value it becomes the value of the max variable. The value is the
difference between the number of heads and tails, which is
heads-tails.
Example:
flips:
h h h t t h h t t t h
heads-tails values:
1 2 3 2 1 2 3 2 1 0 1
So the max gap is 3.
When that works, add similar code to find the biggest difference where
the number of tails is the most more than the number of heads.
*************************************
Harderer:
find the longest run of heads and of tails.
Example:
h h h t t h h t t t h
longest run of heads is 3
longest run of tails is 3