Flipping Coins

Write a project 21-FlippingCoins that uses the Math.random() function to flip a virtual coin to get a result of heads or tails. Flip the coin 100 times and count the number of heads and tails that result, then report that result at the end of the program.

Instructions

This program has more variables than we've used before, so let's think about what we'll need to keep track of.

  1. There's the counting variable for our loop, often i.
  2. There's a counter to keep track of how many heads we flip, maybe called heads.
  3. There's another counter for tails.
  4. We might want a variable for our random flip, randNum, a value that is 0 or 1.

Here's an outline for our code, written half in English, half in JavaScript. This is called pseudocode, and it can be a nice way of thinking about the logic of your program without having to worry about writing it in perfect JavaScript.

set heads counter to 0
set tails counter to 0
start our loop
{
    let randNum = a random number either 0 or 1
    if randNum is 0
    {
        add one to the heads counter
        print out the word "heads" so they know what we got
    }
    else
    {
        add one to the tails counter
        print out the word "tails" so they know what we got
    }
}
Once the loop is done, print out how many heads and
how many tails there were

Once we understand the logic, we can start trying to write it in JavaScript.

let heads = 0;
let tails = 0;
for (i = 0; i < 100; i++)
{
    // code goes here
}
// code goes here

Extension: Modify the program so that the user can specify how many times they wish the coin to be flipped.

Finishing Up

Once your program is working correctly, use your mouse to click-drag over the URL address for your project at the top of the browser window. Copy that link, and give that copied link to the instructor using the procedure given in class.