Search code examples
c++coin-flipping

Coin flip program on c++


I am trying to make a program that will randomly show the outputs of a coin flipping until there are 5 heads in a row and then the program has to stop. I do not have a lot of experience coding so any help is appreciated! So far all I have is a program that outputs the result of a coin flip one time.

#include <iostream>
#include <cstdlib>    
#include <ctime>    

using namespace std;   

int main()   
{   
  srand (time(NULL));
  int flip = (rand()%2)+ 1 ;
  cout<<coin;
  return 0;
}

Solution

  • Use something like this - a while loop. This kind of loop will continue to run while the condition in the parentheses is True. Once it is False it will break out of the loop.

    This may not be exactly what works for you but this is the basic outline of the logic behind what you are trying to achieve.

    Feel free to comment below if you have more questions.

    int numberOfHeads = 0;
    
    while (numberOfHeads <= 5) {
        flipCoin(); // or whatever method is used to call a coin flip -- you can replace this line with whatever logic works best for you
    
        if (coinIsHeads == true) { // again you may need to change the logic in the parentheses for however you wish to test for a head.
           numberOfHeads++;
        }
    }