Heads or Tails Guessing Game Help

Write your question here.
I need help on how I would go about coding this problem. My assignment is to write a program that lets the user guess whether the flip of a coin results in heads or tails. The program randomly generates an integer 0 or 1, which represents head or tail. The program prompts the user to enter a guess and reports whether the guess is correct or incorrect.

The code below is a code that may help because its a random number guessing game.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 int main()
{
	srand(time(0));
	int number = rand() % 101;
	int guess = 0;

	cout << "Guess a magic number between o and 100";

	while (guess != number)
	{
		cout << "\nEnter your guess: ";
		cin >> guess;

		if (guess == number)
			cout << "Yes, the number is\t" << number << endl;
		else if (guess > number)
			cout << "Your number is too high" << endl;
		else
			cout << "Your number is too low" << endl;
	}
	return 0;
}
good
What specific issues are you having?

The code below is a code that may help because its a random number guessing game.


Use the code to write the coin toss program. Once you write it, and have issues, come back with the specific questions.
The program randomly generates an integer 0 or 1, which represents head or tail.


int number = rand() % 101;
==>
int number = rand() % 2; // You only need '0' and '1'

The program prompts the user to enter a guess and reports whether the guess is correct or incorrect.


1
2
3
4
5
6
if (guess == number)
	cout << "Yes, the number is\t" << number << endl;
else if (guess > number)
	cout << "Your number is too high" << endl;
else
	cout << "Your number is too low" << endl;


There is no higher number and lowest number. The only two options here are 'correct' and 'incorrect'. Make use of this hint to complete the rest of the assignment.

Krulcifer Einfolk


Hi Krulcifer,

Thanks for the help and response. I was able to get the game working. However, my while loop is not working. The code runs, but it infinitely displays the answer instead of just once.

I have attached the code below

Thanks,
Ismail

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
	srand(time(0));
	int number = rand() % 2;
	int guess = 0;

	cout << "Guess Heads (0) or Tails (1)\t";
	cin >> guess;
	cout << endl;

	//while (guess != number)
	//{
		if (guess == number)
			cout << "Yes, you are correct" << endl;
		else
			cout << "Incorrect" << endl; 
	//}
	return 0;
}
Consider using a do-while loop.
1
2
3
4
5
6
7
8
9
do
{
    cout << "Guess Heads (0) or Tails (1)\t";
	cin >> guess;
	cout << endl;
	if (guess == number)
			cout << "Yes, you are correct" << endl;
		else			cout << "Incorrect" << endl; 
	} while(guess != number);


Krulcifer Einfolk
Awesome! Thanks for the help :)
Topic archived. No new replies allowed.