DEV Community

May Do
May Do

Posted on

Creating a basic console coin toss in C++

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:
Alt Text

First, let's ask the user how many coin tosses the user wants.
Alt Text

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.
Alt Text

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'.
Alt Text

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:
Alt Text

Top comments (1)

Collapse
 
bighandsorg profile image
Matt Posey

So copied your code into my vs code terminal, but the second string in my terminal is not being recognized. I'm new to this, is there a reason this might happen? Everything looks identical, but the second string is the same color as result right next to it.