In: Computer Science
This is done in C++.
This is a game where one player thinks of a number between 1 and a 1000 and the other player has to guess in 10 tries or less.
Allow two variations: the computer to pick the number and the player guesses or the player to pick the number and the computer to guesses.
1 – Player one picks a number
2 – Player two guesses the number.
3 – Player one either confirms that the guess is correct or tells whether the guess is too high or too low.
4 – Steps 2 and 3 are repeated until count of 10 or the number is guessed correctly.
Notice that you are writing a binary search as you are searching natural numbers from1 to 1000. You may want to make it 1024 since 210 = 1024. This is a sorted array.
C++. game where one player thinks of a number between 1 and a 1000 and the other player has to guess in 10 tries or less.
CODE:
#include <iostream> //included to allow for cout/cin to be used
#include <cstdlib> //include to allow rand() and srand() to be used
#include <time.h>
using namespace std;
int main()
{
bool cont=true;
while(cont)
{
int count=0; // variable count to track number of guesses
int guess;
srand(time(0)); //seeds random number generator.
int x = rand() % 1000;
cout << "Guess a number between 1 -1000.You have only 10 tries\n"; // prompt user to guess a number
std::cin >> guess;
while (guess !=x && count <= 10) // check whether guess is equal or not and count is less than 10
{
if (guess > x)
{
cout << "Too high! Try again. "<<endl;
cin >> guess;
count++;
}
if (guess < x)
{
cout << "Too low! Try again. "<<endl;
cin>>guess;
count++;
}
if (guess == x)
{
cout << "\n\nYou' guessed it right. Good job! "<<endl;
return 0;
}
if (count==10)
{
cout << "\n\nYou're out of guesses!\n";
cout << "\nThe number was - "<<x;
return 0;
}
}
}
return 0;
}