Author Topic: HI-LO Game - Using functions for subtasks  (Read 3658 times)

louiecerv

  • Moderator
  • User
  • *****
  • Posts: 85
HI-LO Game - Using functions for subtasks
« on: January 23, 2006, 12:20:18 AM »
Write an application that will play HI-LO games with the user.  The objective of the game is for the user to guess the computer-generated secret number in the least number of tries. The secret number is an integer between 1 and 100.  When the user makes a guess the program replies with HIGH or LOW depending on whether the guess is higher or lower than the secret number.  The program should display how many tries were needed to guess the number.  The user can play as many games as she wants.

Sample program run:
Please enter your name: Antoine

Hello Antoine

I have selected a number from 1 to 100
Can you guess what this number is?

Enter your guess 50
Your guess is too high.
Enter your guess 25
Your guess is too low.
Enter your guess 35
Your guess is too low.
Enter your guess 40.
Your guess is too low.
Enter your guess 42.
42 is correct Antoine!
Guessing this number took 5 tries.

I have selected a number from 1 to 100
Can you guess what this number is?

Enter your guess
Analyze. Design. Develop. Debug. Deploy. Maintain.

louiecerv

  • Moderator
  • User
  • *****
  • Posts: 85
A solution to the HI-LO game
« Reply #1 on: January 23, 2006, 12:23:37 AM »
Code: [Select]

#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>

using namespace std;
int RandomGen(int MaxNum);

int main()
{
    int Infinite=0;
    string name;
    cout << "Please enter your name: ";
    cin >> name;
    cout << "\nHello " << name << endl;
   
    do
    {
    int guess;
    cout << "\nI have selected a number from 1 to 100\n"
         << "can you guess what this number is? \n\n"
         << "Enter your guess ";
    cin >> guess;
   
    int mynum  = RandomGen(100);
       
        int tries = 0;
        bool isCorrect = false;
       
        do
        {
            tries++;
            if (guess < mynum)
                cout << "Your guess is too low.\n";
            else if (guess > mynum)
                cout << "Your guess is too high.\n";
            else if (guess == mynum)
            {
                cout << guess << " is correct " << name << "!\n";
                cout << "Guessing that number took " << tries << " tries\n";
                isCorrect = true;
                break;
            }
            cout << "Enter your guess ";
            cin >> guess;
        } while (isCorrect == false);
   
    } while ( Infinite==0 );
   
    system("PAUSE");
    return 0;
}

int RandomGen(int MaxNum)
{
    srand ( time(NULL) );
    return rand()% MaxNum + 1;
}

Analyze. Design. Develop. Debug. Deploy. Maintain.