fork download
  1. //OrinTill Qimid CS1A Chapter 4, P. 294, 10
  2. //
  3. /**************************************************************
  4.  * Search number.
  5.  *
  6.  * ____________________________________________________________
  7.  * This program will tell the user if the entered number is vaild or not.
  8.  * ____________________________________________________________
  9.  * INPUT
  10.  * user_num : user number.
  11.  * OUTPUT
  12.  * If the number entered is vaild or not.
  13.  **************************************************************/
  14. #include <iostream>
  15. #include <iomanip>
  16. #include <cmath>
  17. using namespace std;
  18. bool binarySearch(int arr[], int size, int target)
  19. {
  20.  
  21. int left;
  22. int right;
  23. left = 0;
  24. right = size-1;
  25. int mid;
  26. //checking if the number is the first or last number.
  27. if (arr[left] == target)
  28. {
  29. return true;
  30. }
  31. if (arr[right] == target)
  32. {
  33. return true;
  34. }
  35.  
  36. while (left <= right)
  37. {
  38. mid = left + (right - left) / 2;
  39.  
  40. // Check if target is present at mid
  41. if (arr[mid] == target)
  42. {
  43. return true;
  44. }
  45. // If target is greater, ignore the left half
  46. else if (arr[mid] < target) {
  47. left = mid + 1;
  48. }
  49. // If target is smaller, ignore the right half
  50. else {
  51. right = mid - 1;
  52. }
  53. }
  54. return false;
  55. }
  56. int* Sort(int arr[], int size)
  57. {
  58. int lowest;
  59. int var;
  60.  
  61. for (int s = 0; s < size; s++)
  62. {
  63. lowest = arr[s];
  64. for (int i = s+1; i < size; i++)
  65. {
  66. if (lowest > arr[i])
  67. {
  68.  
  69. lowest = arr[i];
  70. var = i;
  71. }
  72.  
  73. }
  74. arr[var] = arr[s];
  75. arr[s] = lowest;
  76.  
  77. }
  78. return arr;
  79.  
  80. }
  81. int main()
  82. {
  83. // Initialize the list of valid charge account numbers
  84. const int SIZE = 18;
  85. int user_num;
  86. bool found = false;
  87. int validNumbers[SIZE] = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
  88. 8080152, 4562555, 5552012, 5050552, 7825877, 1250255,
  89. 1005231, 6545231, 3852085, 7576651, 7881200, 4581002};
  90.  
  91. cout<<"Please enter your user number."<<endl;
  92. cin>>user_num;
  93. found = binarySearch(Sort(validNumbers, SIZE), SIZE, user_num);
  94. if (found == true)
  95. {
  96. cout<<"Your numbers are valid"<<endl;
  97. }
  98. else
  99. {
  100. cout<<"Sorry number is invaild."<<endl;
  101. }
  102.  
  103.  
  104.  
  105. return 0 ;
  106. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Standard output is empty