fork download
  1.  
  2. //Dione Torrevillas CS1A Chapter 8, P. 487, #3
  3.  
  4. /**********************************************************
  5.  * Class: CS1A
  6.  * Chapter 8 Homework - Programming Challenge #3
  7.  * Title: Lottery Winners Modification
  8.  *
  9.  * Description:
  10.  * This program uses binary search to check whether one of
  11.  * the player's ticket numbers matches the winning number.
  12.  *
  13.  * INPUT:
  14.  * This week's winning five-digit lottery number.
  15.  *
  16.  * OUTPUT:
  17.  * A message saying whether a ticket is a winner.
  18.  **********************************************************/
  19.  
  20. #include <iostream>
  21. using namespace std;
  22.  
  23. int main()
  24. {
  25. const int SIZE = 10;
  26.  
  27. // Binary search requires the array to be in ascending order.
  28. const int tickets[SIZE] = {
  29. 13579, 26791, 26792, 33445, 55555,
  30. 62483, 77777, 79422, 85647, 93121
  31. };
  32.  
  33. int winningNumber; //INPUT - Winning lottery number
  34. int first = 0;
  35. int last = SIZE - 1;
  36. bool winner = false;
  37.  
  38. cout << "Enter this week's winning five-digit number: ";
  39. cin >> winningNumber;
  40.  
  41. // Repeatedly check the middle of the remaining search range.
  42. while (first <= last && !winner)
  43. {
  44. int middle = (first + last) / 2;
  45.  
  46. if (tickets[middle] == winningNumber)
  47. winner = true;
  48. else if (tickets[middle] > winningNumber)
  49. last = middle - 1; // Search the lower half.
  50. else
  51. first = middle + 1; // Search the upper half.
  52. }
  53.  
  54. //OUTPUT - Display whether a ticket matched.
  55. if (winner)
  56. cout << "Congratulations! You have a winning ticket." << endl;
  57. else
  58. cout << "None of your tickets won this week." << endl;
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 5348KB
stdin
93121
stdout
Enter this week's winning five-digit number: Congratulations! You have a winning ticket.