The following program is a game in which there is a pile of coins. When the loop runs two players take turns removing coins. Whoever gets the last coin wins the game. ... How can I get the looping to stop when there is a winner?? Right now it still displays the "player 1 please remove coins" output...

#include <iostream>
using namespace std;

int main ()
{
	double pileSize;
	double maxTurn;

	double turn;
	double removed;
	double left;
	
	cout << "Enter the size of the pile: ";
	cin >> pileSize;
	
	cout << "Enter the maximum size of the turn: ";
	cin >> maxTurn;
	
	while (pileSize > 0)
	{
		cout << "Player 1, it is your turn to remove chips!";						//Player 1's turn
		cin >> turn;
		
		if (turn > maxTurn || turn < 1)												//Validity
		{
			cout << "Invalid turn, please retry... ";
			cin >> turn;
		}
		
		removed += turn;															//Keep a running total of turns
		left = pileSize - removed;													//Subtract total from pile
		
		cout << "There are " << left << " chips remaining.";						//Display remaining in pile
		if (left < 1)
			cout << " Player 1, You have one the game!" << endl;					//Player 1 wins game! if there are 0 chips left
		else
		{																			//if there are chips remaining, another turn
			cout << " Player 2, it is your turn to remove chips!";
			cin >> turn; 
		
		
		if (turn > maxTurn || turn < 1)												//validity
		{
			cout << " Invalid turn, please retry... ";								
			cin >> turn;
		}
		
		removed += turn;															//keep running total
		left = pileSize - removed;													//display remaining
		cout << "There are " << left << " chips remaining.";						//if there are no chips left, player 2 wins
		if (left < 1)
			cout << " Player 2, you have won the game! " << endl;
		}
																					
	}
	
    return 0;
}
Salem commented: >10 posts, and still no code tags - guess you earn a prize -4

Recommended Answers

All 3 Replies

There are a number of ways to get out of the loop. One way is to put the break statement when someone wins the game:

if (left < 1)
{
cout << " Player 1, You have one the game!" << endl; 
break;
}

Else, you can set a flag to true whenever someone wins the game, and then put the check for the flag as one of the condition of the while-loop.

There are some more problems with your codes:

1. You never initialized the variable "removed", yet you used it to keep track of the turns:

removed += turn; //Keep a running total of turns

This will lead to unpredictable behaviour.

2. Why use double for all the variables? Since you are dealing with discrete items like coins, you should use integer instead.

3. You should use while-loop for your validity checks. Using if-statement will only check once.

Ok, that makes sense thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.