"while" loop problem

the "while" continues to make the program loop when the correct answer is stored. How would i fix this?



#include <iostream>

int NumberGame(int x)
{

int y = 6;

std::cout << "Guess the number between 1 and 6" << std::endl;

std::cin >> x;

if (x == 6)
std::cout << "wow you win" << std::endl;


else if (x < 6)

std::cout << "you lose" << std::endl;

else if (x > 6)
std::cout << "your not even trying" << std::endl;

return x;
}

int main()
{
int x = 1;

while (x < 6 | x > 6)
NumberGame(x);
return 0;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std; // now you can use cout instead of std::cout

// Returns true (1) until the correct answer is found. Then it returns false (0).
bool NumberGame(int x){
        int y; // y is the user's input

	cout << "Guess the number between 1 and 6" << endl;
	cin >> y;
	
	if (y == x){ // If answer is correct
		cout << "wow you win" << endl;
		return 0; // Return false and ends NumberGame() function
	}
	else if (y > 6 || y < 1){ // If answer is outside of parameters 
	    cout << "you're not even trying" << endl;
	}
	else { // If answer is within parameters but is incorrect
		cout << "you lose" << endl;
	}
	
	return 1; // Returns true
}

int main(){
	int x = 6; // x is the correct answer

	while (NumberGame(x)); // While NumberGame() returns true (1)

	return 0;
}
Last edited on
Thanks for this, didn't even cross my mind to use bool.
Topic archived. No new replies allowed.