fork download
  1. //Cameron Pham CS1A Chapter 5, p. 298, #20
  2. //
  3. /******************************************************************************
  4. * GUESS RANDOM NUMBER
  5. * ______________________________________________________________________________
  6. * This program accepts an integer value for a guess of a random number. It
  7. * Generates a random number.
  8. * ______________________________________________________________________________
  9. * INPUT
  10. * Random number // # generated by computer
  11. * Guess // User's guess
  12. *
  13. * OUTPUT
  14. * Wrong or correct guess
  15. *
  16. *******************************************************************************/
  17. #include <iostream>
  18. #include <cstdlib>
  19. #include <ctime>
  20. using namespace std;
  21.  
  22. int main()
  23. {
  24. // Initialize variables
  25. int randomNumber; // Random number generated by the computer
  26. int guess; // User's guess
  27.  
  28. // Seed the random number generator
  29. srand(time(0));
  30.  
  31. // Generate a random number between 1 and 100
  32. randomNumber = rand() % 100 + 1;
  33.  
  34. // Continue asking for guesses until the correct number is entered
  35. do
  36. {
  37. cout << "Guess a number between 1 and 100: ";
  38. cin >> guess;
  39.  
  40. // Check whether the guess is too high or too low
  41. if (guess > randomNumber)
  42. {
  43. cout << "Too high, try again." << endl;
  44. }
  45. else if (guess < randomNumber)
  46. {
  47. cout << "Too low, try again." << endl;
  48. }
  49.  
  50. } while (guess != randomNumber);
  51.  
  52. // Display congratulations when the correct number is guessed
  53. cout << "Congratulations! You guessed the number!" << endl;
  54.  
  55. return 0;
  56. }
Success #stdin #stdout 0s 5328KB
stdin
5
67
23
49
57

stdout
Guess a number between 1 and 100: Congratulations! You guessed the number!