fork download
  1. //Diego Martinez CSC5 Chapter 8, P.487, #3
  2. /*******************************************************************************
  3. * DISPLAY LOTTERY WINNERS (BINARY SEARCH)
  4. * ______________________________________________________________________________
  5. * This program allows the user to enter this week's 5-digit lottery
  6. * number and checks whether it matches any of the 10 winning lottery ticket
  7. * numbers. It then displays a message whether or not the user has a winning
  8. * number.
  9. *
  10. * Computation is based on the Formula:
  11. * tickets[i] = winningNumber
  12. *______________________________________________________________________________
  13. * INPUT
  14. * 5-digit lottery number entered by the user
  15. *
  16. * OUTPUT
  17. * A message stating whether one of the lottery tickets is a WINNER or not
  18. *******************************************************************************/
  19. #include <iostream>
  20. using namespace std;
  21.  
  22. int main()
  23. {
  24.  
  25. // sorted Array of lottery numbers
  26. int tickets[10] = {
  27. 13579, 26791, 26792, 33445, 55555,
  28. 62483, 77777, 79422, 85647, 93121
  29. };
  30. int winningNumber;
  31. bool winner = false;
  32. int first = 0;
  33. int last = 9;
  34. int middle;
  35.  
  36. // Ask user for winning number
  37. cout << "Enter this week's winning 5-digit number: ";
  38. cin >> winningNumber;
  39.  
  40. // Binary search
  41. while (first <= last)
  42. {
  43. middle = (first + last) / 2;
  44. if (tickets[middle] == winningNumber)
  45. {
  46. winner = true;
  47. break;
  48. }
  49. else if (tickets[middle] > winningNumber)
  50. {
  51. last = middle - 1;
  52. }
  53. else
  54. {
  55. first = middle + 1;
  56. }
  57. }
  58. // Display Result
  59. if (winner)
  60. {
  61. cout << "Congratulations! One of your tickets is a WINNER!" << endl;
  62. }
  63. else
  64. {
  65. cout << "Sorry, none of your tickets matched this week's winning number." << endl;
  66. }
  67. return 0;
  68. }
Success #stdin #stdout 0.01s 5308KB
stdin
13579
stdout
Enter this week's winning 5-digit number: Congratulations! One of your tickets is a WINNER!