fork download
  1. // Marvyn Jesse De La Torre CS1A Chapter 7, pg. 447, #13
  2. //
  3. /****************************************************************************
  4.  * RUN THE LOTTERY APPLICATION
  5.  *
  6.  * This program accepts five random lottery digits from 0 through 9.
  7.  * It asks the user to enter five digits and compares the user's numbers
  8.  * with the lottery numbers. It displays the lottery numbers and the number
  9.  * of matching digits. Matching all five digits makes the user a grand
  10.  * prize winner.
  11.  *
  12.  * INPUT
  13.  * user // The five lottery digits entered by the user
  14.  *
  15.  * OUTPUT
  16.  * lottery // The five randomly generated lottery digits
  17.  * matches // Number of matching digits
  18.  * prizeMessage // Whether the user won the grand prize
  19.  ****************************************************************************/
  20.  
  21. #include <iostream>
  22. #include <cstdlib>
  23. #include <ctime>
  24. #include <limits>
  25. using namespace std;
  26.  
  27. int main()
  28. {
  29. const int SIZE = 5;
  30. int lottery[SIZE];
  31. int user[SIZE];
  32. int matches = 0;
  33.  
  34. // Seed the random number generator.
  35. srand(static_cast<unsigned int>(time(0)));
  36.  
  37. // Generate five random lottery digits from 0 through 9.
  38. for (int i = 0; i < SIZE; i++)
  39. {
  40. lottery[i] = rand() % 10;
  41. }
  42.  
  43. // Ask the user to enter five digits and validate each one.
  44. cout << "Enter five lottery digits (0 through 9).\n";
  45. for (int i = 0; i < SIZE; i++)
  46. {
  47. cout << "Enter digit " << i + 1 << ": ";
  48. cin >> user[i];
  49.  
  50. while (cin.fail() || user[i] < 0 || user[i] > 9)
  51. {
  52. cout << "Invalid digit. Enter a number from 0 through 9: ";
  53. cin.clear();
  54. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  55. cin >> user[i];
  56. }
  57. }
  58.  
  59. // Compare each user digit with the lottery digit in the same position.
  60. for (int i = 0; i < SIZE; i++)
  61. {
  62. if (user[i] == lottery[i])
  63. {
  64. matches++;
  65. }
  66. }
  67.  
  68. // Display the lottery numbers and matching digit count.
  69. cout << "\nLottery numbers: ";
  70. for (int i = 0; i < SIZE; i++)
  71. {
  72. cout << lottery[i] << " ";
  73. }
  74.  
  75. cout << "\nMatching digits: " << matches << endl;
  76.  
  77. // Check whether all five digits match.
  78. if (matches == SIZE)
  79. {
  80. cout << "Congratulations! You are the grand prize winner!\n";
  81. }
  82.  
  83. return 0;
  84. }
Success #stdin #stdout 0.01s 5320KB
stdin
4
2
9
7
3
stdout
Enter five lottery digits (0 through 9).
Enter digit 1: Enter digit 2: Enter digit 3: Enter digit 4: Enter digit 5: 
Lottery numbers: 7 0 3 1 3 
Matching digits: 1