CSci 101: Homework 2
Objectives
In this programming assignment you will design, write and test a computer
program with branching statements and loops. The problem description is
given below. If you would like a more challenging program, see the one
at the end of this assignment.
Problem
Write a Java program that simulates flipping coins and counts the coin
flips. The program should ask the user how many times to flip the coin, then
simulate flipping the coin that many times (using a random number
generator), prints a symbol (H or T) for each coin flip, and provides a
summary giving the total number of heads and tails.
Discussion
As always, your program should first output an introductory message to the
user explaining what the program does. Then prompt the user to enter the
number of coins to flip. The program will need a loop, and the instructions
inside the loop should deal with flipping the coin once.
You can simulate the coin flip with a random number generator. One way to do
that in Java is to use the Math.random method.
When you need to simulate a coin flip, you call the Math.random method
to generate a random number x between 0 and 1 (greater than or
equal to 0, but strictly less than 1). This random number has a uniform
distribution, so the probability that it's less than 0.5 is one half. Thus,
the condition
if (Math.random() < 0.5)
can be used to decide when the coin is flipped heads. If it is heads, print
an H and increase the counter for the number of heads. Otherwise, print T
and increase the tail counter.
Sample Execution
This program will simulate flipping a fair coin.
How many times would you like the coin to be flipped? 50
Here is the sequence of coin flips:
THHTHTHHTTTHTHTTTTHHTHTHTHHTHTHHTHTHHTTHTTTHHHTHTT
There were 24 heads and 26 tails.
Testing
Run your program several times. You should get different
results each time.
Deliverables
Turn in the following items:
- A printout of your program on paper
- A printout showing the 2 runs of your program with 100 coinflips each.
Grading will be as for the last homework assignment.
Challenge program
If you prefer, you can try this challenge program instead of the one
above. Change from flipping a coin to tossing a pair of dice. Keep
track of the sum of the dice, and print the output in a histogram.
Use a * for each time a sum occurs, so if there are eight 7's, then
after 7 print out ********. Here's what a sample run might look like:
This program will simulate tossing a pair of dice.
How many times would you like the dice to be tossed? 20
Here is the sequence of sums, one for each toss:
8 6 3 9 6 7 2 11 5 8 4 7 9 9 6 10 7 5 11 7
2: *
3: *
4: *
5: **
6: ***
7: ****
8: **
9: **
10: *
11: **
12: