home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter02 / guess_my_number.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2003-10-21  |  663 b   |  36 lines

  1. // Guess My Number
  2. // The classic number guessing game
  3.  
  4. #include <iostream>
  5. #include <cstdlib>
  6. #include <ctime>
  7.  
  8. using namespace std;
  9.  
  10. int main()
  11. {
  12.     srand(time(0)); // seed random number generator 
  13.  
  14.     int theNumber = rand() % 100 + 1; // random number between 1 and 100
  15.     int tries = 0, guess;
  16.     
  17.     cout << "\tWelcome to Guess My Number\n\n";
  18.  
  19.     do
  20.     {
  21.         cout << "Enter a guess: ";
  22.         cin >> guess;
  23.         ++tries;
  24.  
  25.         if (guess > theNumber)
  26.             cout << "Too high!\n\n";
  27.  
  28.         if (guess < theNumber)
  29.             cout << "Too low!\n\n";
  30.  
  31.     } while (guess != theNumber);
  32.  
  33.     cout << "\nThat's it! You got it in " << tries << " guesses!\n";
  34.  
  35.     return 0;
  36. }