fork download
  1. // Amari Mosley CSC5 Chapter 5, P. 298, #20
  2. //
  3. /**************************************************************
  4. *
  5. * COMPUTE RANDOM NUMBER GAME
  6. *______________________________________________________________
  7. * This program generates a random number and asks the user to
  8. * guess it. It provides feedback ("Too high, try again" or
  9. * "Too low, try again") using a loop that repeats until the
  10. * user guesses the correct number.
  11. *
  12. * INPUT
  13. * guess : Integer value guessed by the user
  14. *
  15. * OUTPUT
  16. * feedback : Hints guiding the user until the guess is correct
  17. *
  18. **************************************************************/
  19.  
  20. #include <iostream>
  21. #include <cstdlib>
  22. #include <ctime>
  23.  
  24. using namespace std;
  25.  
  26. int main() {
  27. // Seed the random number generator
  28. srand(static_cast<unsigned int>(time(0)));
  29.  
  30. // Generate a random number (e.g., between 1 and 10)
  31. const int SECRET_NUMBER = (rand() % 10) + 1;
  32.  
  33. // INPUT
  34. int guess;
  35.  
  36. cout << "I have generated a random number between 1 and 10.\n";
  37. cout << "Can you guess what it is?\n\n";
  38.  
  39. // Loop until the user correctly guesses the random number
  40. do {
  41. cout << "Enter your guess: ";
  42. cin >> guess;
  43.  
  44. if (guess > SECRET_NUMBER) {
  45. cout << "Too high, try again.\n";
  46. } else if (guess < SECRET_NUMBER) {
  47. cout << "Too low, try again.\n";
  48. } else {
  49. cout << "\nCongratulations! You guessed the correct number: " << SECRET_NUMBER << endl;
  50. }
  51. } while (guess != SECRET_NUMBER);
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 5324KB
stdin
1
2
3
4
5
6
7
8
9
10
stdout
I have generated a random number between 1 and 10.
Can you guess what it is?

Enter your guess: 
Congratulations! You guessed the correct number: 5