How to write this JavaScript program? "Toss a coin 100 times and print the number of heads and tails

Jaden Easton

Jaden Easton

Answered question

2021-09-23

How to write this JavaScript program? "Toss a coin 100 times and print the number of heads and tails."

Answer & Explanation

davonliefI

davonliefI

Skilled2021-09-24Added 79 answers

Here's a simple way to do it. We'll define two variables to hold the number of heads and tails, respectively. Then we'll use a for loop and the Math.random() function to simulate 100 coin flips. At the end, we print the results.
let heads = 0.let tails = 0.
for (let step = 0. step < 100. step++) {
flip = Math.floor(Math.random() * 2).
if (flip === 0) {
heads += 1.
}
else {
tails += 1.
}
}
console.log(`The number of heads is ${heads}.`).
console.log(`The number of tails is ${tails}.`).

Do you have a similar question?

Recalculate according to your conditions!

Ask your question.
Get an expert answer.

Let our experts help you. Answer in as fast as 15 minutes.

Didn't find what you were looking for?