In: Computer Science
Use a JavaScript program to:
Stimulate a coin tossing environment using random functions and using a for loop - toss the coin 100 times and print the number of heads and tails.
A detailed answer would be appreciated, I would like to learn from it rather than just know the answer. Thanks in advance!
let heads = 0; //variable to store heads value
let tails = 0; //variable to store tails value
for(let i=0; i<100; i++){
let random = Math.random(); //randomly generating number
if(random >= 0.5){ //condition to check heads or tails
heads++; // increase heads count
}
else{
tails++; // increase tails count
}
}
console.log("heads = " + heads);
console.log("tails = " + tails);
In the first two lines heads and tails are variables to store heads and tails count.
Then in the third line we initialized for loop which run for 100 times.
In the forth line we initialized variable to store random number and that random number is generted from Math.random() function and this Math.random() will only generate number between 0 to 1 .
If you want to generate random numbers between specific number you have to use Math.floor(Math.random() * 10) . Number 10 in indicates we want to generate random number between 0 to 9 which are 10 values in total
And in fifth line we used if conditon to check if the random number is grater than 0.5 or not. if the condition is satisfieed then the code in curly braces is excuted or that code will be skippped
heads++ will increase heads count to +1 that is only if previous if condition is satisfied
If that if condition is not satsfied then the code in else curly braces will be executed
Finally console.log will print the value inside the brackets .And in the brackets if you ive value between quotes it will print as it is watever you give or you can print variable you intialized earlier by entering variable name (not in between brackets) .
If you want to print your variable value and enter a specific value you can use + operator to combine both
Note: Code after // is a comment compiler will not read it. it is just for developer information
This is my code and its output , I used Visual studio to write and run code