fork download
  1. //Ryan Robateau CSC5 Chapter 8, p. 487, #3
  2. //
  3. /*******************************************************************************
  4.  *
  5.  * Determine Winning Numbers (Binary Search Edition)
  6.  * _____________________________________________________________________________
  7.  * This program will prompt the user to enter 5 number for the lottery. The
  8.  * program will then call a function to verify of the numbers entered by the
  9.  * user are wining numbers. If the numbers are winning numbers then the program
  10.  * will then congradulate the user, if not then the program will tell the user
  11.  * that they go it wrong.
  12.  * _____________________________________________________________________________
  13.  ******************************************************************************/
  14. #include <iostream>
  15. #include <iomanip>
  16. using namespace std;
  17.  
  18. float binarySearch(float lotteryNums[], int size, int user);
  19.  
  20. int main()
  21. {
  22. const int SIZE = 10;
  23. float luckNums[SIZE] = {13579, 26791, 26792,
  24. 33445, 55555, 62483,
  25. 77777, 79422, 85647,
  26. 93121};
  27. float userNums;
  28. int match;
  29.  
  30. cout << "Hello Welcome To The Lottery" << endl;
  31. cout << "Please Enter 5 Numbers: " << endl;
  32. cin >> userNums;
  33.  
  34. match = binarySearch(luckNums, SIZE, userNums);
  35.  
  36. if( match == -1)
  37. {
  38. cout << "UNLUCKY!" << endl;
  39. cout << "Not Winning Numbers" << endl;
  40. }
  41. else
  42. {
  43. cout << "CONGRATS!" << endl;
  44. cout << "You Entered Winning Numbers" << endl;
  45.  
  46. }
  47.  
  48. return 0;
  49. }
  50.  
  51. float binarySearch(float lotteryNums[], int size, int user)
  52. {
  53. int first;
  54. int last = size - 1;
  55. int middle;
  56. int position = -1;
  57. bool found = false;
  58.  
  59. while(!found && first <= last)
  60. {
  61. middle = (first + last) / 2;
  62. if(lotteryNums[middle] == user)
  63. {
  64. found = true;
  65. position = middle;
  66. }
  67. else if(lotteryNums[middle] > user)
  68. {
  69. last = middle - 1;
  70. }
  71. else
  72. {
  73. first = middle + 1;
  74. }
  75. }
  76. return position;
  77. }
Success #stdin #stdout 0s 5304KB
stdin
13579
stdout
Hello Welcome To The Lottery
Please Enter 5 Numbers: 
CONGRATS!
You Entered Winning Numbers