Question #256153

Write a program that keeps asking a user to guess a number until they get the secret number. Indicate to the user if the guess is too low or high and also indicate how many guesses were taken to get the secret number. Assume that that the secret number is 37. Use the following sample run as a reference to test your results:

Expert's answer

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int n, ans, attempt = 0;
    srand(time(0));
    n = rand() % 100 + 1; 
    cout << "Guess My number Game\n\n";

    do
    {
        cout << "Enter a ans between 1 and 100 : ";
        cin >> ans;
        attempt++;

        if (ans > n)
            cout << "Too high!\n\n";
        else if (ans < n)
            cout << "Too low!\n\n";
        else
            cout << "\nCorrect! Guesses: " << attempt << '\n';
    } while (ans != n);

    return 0;
}

LATEST TUTORIALS
APPROVED BY CLIENTS