fork download
  1. //Ryan Robateau CSC5 Chapter 8, P. 487, #4
  2. /******************************************************************************
  3.  * Validate Charge Number
  4.  * ____________________________________________________________________________
  5.  * This program accepts user input in the form of an Account Number and then
  6.  * compares it to each value in an array to determine its validity.
  7.  * ____________________________________________________________________________
  8.  *****************************************************************************/
  9. #include <iostream>
  10. using namespace std;
  11.  
  12. void selectionSort(int ChargeNum[]);
  13. int binarySearch(int ChargeNum[], int chargeNumber);
  14.  
  15. const int SIZE = 18;
  16. int main() {
  17. int positionFound;
  18. int chargeNumber;
  19. int ChargeNum[SIZE] = {5658845, 4520125, 7895122,
  20. 8777541, 8451277, 1302850,
  21. 8080152, 4562555, 5552012,
  22. 5050552, 7825877, 1250255,
  23. 1005231, 6545231, 3852085,
  24. 7576651, 7881200, 4581002};
  25.  
  26. cout << "Please Enter your account number: ";
  27. cin >> chargeNumber;
  28.  
  29. selectionSort(ChargeNum);
  30.  
  31. positionFound = binarySearch(ChargeNum, chargeNumber);
  32.  
  33. if (positionFound == -1)
  34. cout << "\nSorry! The number is invalid.";
  35. else
  36. cout << "\nThe number is valid!";
  37. return 0;
  38. }
  39. void selectionSort(int ChargeNum[])
  40. {
  41. int startScan;
  42. int minIndex;
  43. int minValue;
  44.  
  45. for(startScan = 0; startScan < (SIZE - 1); startScan++){
  46. minIndex = startScan;
  47. minValue = ChargeNum[startScan];
  48. for (int index = startScan + 1; index < SIZE; index++){
  49. if (ChargeNum[index] < minValue){
  50. minValue = ChargeNum[index];
  51. minIndex = index;
  52. }
  53. }
  54. ChargeNum[minIndex] = ChargeNum[startScan];
  55. ChargeNum[startScan] = minValue;
  56. }
  57. }
  58.  
  59. int binarySearch(int ChargeNum[], int chargeNumber){
  60. int first = 0;
  61. int last = SIZE - 1;
  62. int middle;
  63. int position = -1;
  64. bool found = false;
  65. while (!found && first <= last){
  66. middle = (first + last) / 2;
  67. if (ChargeNum[middle] == chargeNumber){
  68. found = true;
  69. position = middle;
  70. }
  71. else if (ChargeNum[middle] > chargeNumber)
  72. last = middle - 1;
  73. else
  74. first = middle + 1;
  75. }
  76. return position;
  77. }
Success #stdin #stdout 0s 5304KB
stdin
7576651
stdout
Please Enter your account number: 
The number is valid!