This is a small program that will simulate a coin toss for however many times specified by the user. It randomly generates the numbers one and two. When the number generated is one it will display 'heads', and when the number generated is two it will display 'tails. Pretty simple. The expected output should look something like this:
First, let's ask the user how many coin tosses the user wants.
Now that we have a number, we know where to stop our loop! For each iteration, we're going to simulate a coin toss and log the result into the console. Let's make another function called coinToss that would 'toss the coin' to make our code a little neater.
This is where all the real action takes place. In the coinToss function, we're going to need a number that's either 1 or 2, so we're going to use rand() which will randomly generates a number for us. Set the range of the random numbers to only be between the 1 and 2. Don't forget that in order to use rand(), you'll also need to use srand(time(NULL)). Once we have a random number, we need to make sure that 1 will give us 'heads' and 2 will give us 'tails'.
The program should randomly return a string of 'heads' or 'tails' until the number of coin tosses the user specified is reached. And that's all! You've just created a coin toss simulator. The whole program that was used looks like this:
Top comments (1)