Visual C++ - Guess Number in 5 attempts
Guessing a Number (0 - 100) would be interesting program. Here you can find the complete source code in Visual C++ Programming Language.
The program will generate a random number between 0 - 100 and keep it as a secret number. Your job is find out the secret number in 5 attempts. Each time you guess you will get the message like given below:
1. Very High or Very Low (> 50)
2. High or Low (<50 and > 30)
3. Moderately High or Moderately Low (<30 and > 15)
4. Somewhat High or Somewhat Low (< 15)
In case, the secret number is 86, if you enter your choice as 10, then you will get the message "Very Low". It means you have to increase your choice by at least 50. Let's say the second choice you give out is 60, then the message "Moderately Low". Then you can assume the secret number is in between (75 - 90). Then your 3rd choice would be 83 and the message "Somewhat Low". Now you know the secret number is in between 84 - 90. Then your 4th choice is: 86. Now you won and found out the correct number in 4 attempts.
Source Code
#include <iostream>
#include <math.h>
#include <conio.h>
#include <process.h>
#include <string.h>
void main()
{
int i, n, diff;
int x = rand() % 100;
int bMoveHigher = 0;
int bGuessedCorrectly = 0;
std::cout << "Welcome to Guess a Word Program\n";
for (i = 1; i <= 5; i++)
{
std::cout << "ATTEMPT %d: Enter the your number: ", i;
std::cin >> n;
if (n == x)
{
std::cout << "Congrats! You have guessed the number correctly\n";
bGuessedCorrectly = 1;
break;
}
diff = (int)(fabs(x - n));
if(x > n)
bMoveHigher = 1;
if(diff >= 50)
{
if (bMoveHigher == 0)
std::cout << "Your guess is VERY HIGH\n";
else
std::cout << "Your guess is VERY LOW\n";
}
else if (diff >= 30)
{
if (bMoveHigher == 0)
std::cout << "Your guess is HIGH\n";
else
std::cout << "Your guess is LOW\n";
}
else if (diff >= 15)
{
if (bMoveHigher == 0)
std::cout << "Your guess is MODERATELY HIGH\n";
else
std::cout << "Your guess is MODERATELY LOW\n";
}
else
{
if (bMoveHigher == 0)
std::cout << "Your guess is SOMEWHAT HIGH\n";
else
std::cout << "Your guess is SOMEWHAT LOW\n";
}
}
if (bGuessedCorrectly == 0)
{
std::cout << "Unfortunately you did not guess it correctly. The correct number is: " << x <<”\n";
}
}
Output
Welcome to Guess a Word Program (0-100) with in 5 attempts.
ATTEMPT 1: Enter the your number: 50
Your guess is MODERATELY HIGH
ATTEMPT 2: Enter the your number: 28
Your guess is SOMEWHAT HIGH
ATTEMPT 3: Enter the your number: 24
Your guess is SOMEWHAT HIGH
ATTEMPT 4: Enter the your number: 22
Your guess is SOMEWHAT LOW
ATTEMPT 5: Enter the your number: 23
Congrats! You have guessed the number correctly
Press any key to continue . . .
|