3

I have to write a program that runs a loop for a coin toss. I am supported to enter a number into the console and have it run a loop of the coin toss for that many times. I need to use nested loops. I have been working on this for hours and cannot make it work.

The console i/o is supposed to look like below:
Enter the number of tosses to perform [0=exit]: 3 Heads Tails Heads

Enter the number of tosses to perform [0=exit]: 2 Tails Tails

Enter the number of tosses to perform [0=exit]: 0

This is the code i have so far:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main ()
{
  srand(time(0));rand(); 
  int result = rand() % 2;
  while (true)
  {
    int n; // this many tosses
    cout << "How many tosses";
    cin >> n;
    cin.ignore (1000, 10);
    if (n == 0)
      break;

    for (int i = 0; i < n; i++)
    //random number generator
    {    
      if (result == 0)
        cout<< "Heads"<<endl;
      else if (result == 1)
        cout << "Tails"<<endl;
      else if (result != 0 || result !=1) 
        return 0;
    } //for 
  }//while
}//main
ch0kee
  • 736
  • 4
  • 12
David
  • 389
  • 5
  • 22

3 Answers3

2

Your for loop doesn't have the part that you are actually trying to execute inside of {}. Try adding the braces around the part you want to loop and see if that fixes it for you.

I edited the indentation in your code to show you the only line that will actually be looping (the srand(time(0)))

jprofitt
  • 10,874
  • 4
  • 36
  • 46
1
  1. You need brackets around the loop block, i.e.

    for( int i = 0; i < n; i++ )
    {
        // Code goes here
    }
    
  2. As shown above, you need to initialize i.

  3. Put the seeding of rand() before the while(...) loop.

Drew Chapin
  • 7,779
  • 5
  • 58
  • 84
Fredrik Ullner
  • 2,106
  • 2
  • 22
  • 28
0

You need to move int result = rand() % 2; inside your for loop! Otherwise you will get the same result every single time until you restart the application.

for (int i = 0; i < n; i++)
        //random number generator
{    
    int result = rand() % 2;
    if (result == 0)
         cout<< "Heads"<<endl; /* to make your output look like your example you should removed the <<endl from here */
    else if (result == 1)
        cout << "Tails"<<endl; /* and here */
    else if (result != 0 || result !=1) 

        return 0;
} //for 

/* and put it here */
cout << endl;
Drew Chapin
  • 7,779
  • 5
  • 58
  • 84