fork download
  1. //Amari Mosley CSC5 Chapter 8, P. 487, #3
  2.  
  3. /*******************************************************************************
  4. *
  5. * BNARY SEARCH LOTTERY WINNERS
  6. * ______________________________________________________________________________
  7. *
  8. * This program initializes an array with a lottery ticket buyer's
  9. * 10 lucky 5-digit combinations, lets the player enter this week's
  10. * winning 5-digit number, and performs a binary search to report
  11. * whether or not one of the tickets is a winner.
  12. *
  13. *
  14. * ______________________________________________________________________________
  15. *
  16. *
  17. * INPUT
  18. * winningNumber : The 5-digit winning number entered by the user
  19. * OUTPUT
  20. * resultMessage : Indicates whether the ticket is a winner or not
  21. *
  22. *
  23. ********************************************************************************/
  24. #include <iostream>
  25. using namespace std;
  26. int main ()
  27. {
  28. // Constants
  29. const int NUM_TICKETS = 10;
  30.  
  31. // INPUT
  32. int winningNumber;
  33.  
  34. // Initialize Program variables
  35. int tickets[NUM_TICKETS] = { 13579, 26791, 26792, 33445, 55555,
  36. 62483, 77777, 79422, 85647, 93121 };
  37. int first = 0;
  38. int last = NUM_TICKETS - 1;
  39. int middle;
  40. bool found = false;
  41.  
  42. // Get this week's winning 5-digit number from the user
  43. cout << "Enter this week's 5-digit winning number: ";
  44. cin >> winningNumber;
  45.  
  46. // Search the array for the winning number using binary search
  47. while (!found && first <= last)
  48. {
  49. middle = (first + last) / 2;
  50. if (tickets[middle] == winningNumber)
  51. {
  52. found = true;
  53. }
  54. else if (tickets[middle] > winningNumber)
  55. {
  56. last = middle - 1;
  57. }
  58. else
  59. {
  60. first = middle + 1;
  61. }
  62. }
  63.  
  64. // Output Result
  65. if (found)
  66. {
  67. cout << "Congratulations! You have a winning ticket!" << endl;
  68. }
  69. else
  70. {
  71. cout << "Sorry, none of your tickets are winners this week." << endl;
  72. }
  73.  
  74. return 0;
  75. }
Success #stdin #stdout 0.01s 5356KB
stdin
77777
stdout
Enter this week's 5-digit winning number: Congratulations! You have a winning ticket!