• If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

View

# Exercises - Random Values

last edited by 3 years ago

Save these exercises as "10_exercise_1.t", "10_exercise_2.t", etc.

Remember to work on the basic exercises first.  The extensions can get quite challenging.  That said, if you see an extension that really interests you, go ahead and work on it.  Just remember that you are responsible for at least attempting all of the basic exercises unless they are marked as [Challenge].

1. (a) Create a program that simulates the flipping of a coin N times and reports "heads" or "tails" to the screen, where N is a number specified by the user.

Extension:

(b) Keep track of the number of "heads" and "tails" and report the total of each at the end of the program.

(c) If the user specifies too many flips (you'll need to figure out how many can be displayed on the screen), then don't output the result of each flip.  Just count the results and report them at the end (in a proper simulation, we usually perform thousands of trials).

(d) For large numbers of flips, report the percentage of "heads" and "tails", rather than the actual number of flips.

 Hint 1 Hint 2 Hint 3 Hint 4 ask the user for N for count :=1 to N var heads, tails : int if the coin lands heads, heads:=heads+1; initialize each to zero at start if N is small enough, display each result else don't display anything until the very end percent heads = (# heads)/(total flips)

2. (a) Create a program that simulates the rolling of N 6-sided dice, where N is a number specified by the user.  The program should display the roll of each die and the total of the dice.  For example, if the user requested 3 rolls:

Roll 1 = 4

Roll 2 = 5

Roll 3 = 1

Total = 10

Extension:

(b) Allow the user to specify how many sides are on the die.  Six is standard, but there are dice out there with 4, 6, 8, 10, 12, 20, or 30 sides.

(c)  If the user specifies too many rolls, then just report the final results of all the rolls (e.g., how many ones, twos, threes, etc.). Note: Assume 6-sided dice only.

(d)  For large numbers of rolls, report the ones/twos/threes/etc as percentages. Note: Assume 6-sided dice only.

 Hint 1 Hint 2 as each die is rolled, keep a running total total := total + roll get user input on # of sides (userSides) randint ( numSides, 1, userSides)

3. (a) Ask the user N single-digit random addition questions (i.e., only using numbers between 1 and 9), where N is the number of questions requested by the user.  Provide appropriate feedback on whether the user is right or wrong.  For example, the output (with user input in bold) might look like this:

That is correct!

Sorry!  The correct answer is 7 + 6 = 13

...

(b) Allow the user to specify how big or small the question numbers should be.  For example, the user might only want questions using numbers from 10 to 100.