fork download
  1. //Cameron Pham CS1A Chapter 8, p. 487, #4
  2. //
  3. /******************************************************************************
  4. * CHARGE ACCOUNT VALIDATION
  5. * ______________________________________________________________________________
  6. * This program accepts an integer value for an account number and determines
  7. * if the number is valid.
  8. * ______________________________________________________________________________
  9. * INPUT
  10. * Account number // Charge account number
  11. *
  12. * OUTPUT
  13. * Validation // Whether or not the account exists or not
  14. *******************************************************************************/
  15. #include <iostream>
  16. using namespace std;
  17. int main()
  18. {
  19. // Initialize Variables
  20. const int SIZE = 18;
  21. int accountNumbers[SIZE] =
  22. {
  23. 5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
  24. 8080152, 4562555, 5552012, 5050552, 7825877, 1250255,
  25. 1005231, 6545231, 3852085, 7576651, 7881200, 4581002
  26. };
  27. int accountNumber; // Account number entered by the user
  28. int minIndex; // Index of the smallest value
  29. int temp; // Temporary variable for swapping
  30. int first; // First array position to search
  31. int last; // Last array position to search
  32. int middle; // Middle array position
  33. bool isValid = false; // Indicates whether the account is valid
  34. // Sort the array using selection sort
  35. for (int start = 0; start < SIZE - 1; start++)
  36. {
  37. minIndex = start;
  38. for (int count = start + 1; count < SIZE; count++)
  39. {
  40. if (accountNumbers[count] < accountNumbers[minIndex])
  41. {
  42. minIndex = count;
  43. }
  44. }
  45. // Swap the smallest value into its correct position
  46. temp = accountNumbers[start];
  47. accountNumbers[start] = accountNumbers[minIndex];
  48. accountNumbers[minIndex] = temp;
  49. }
  50. // Ask the user to enter a charge account number
  51. cout << "Enter a charge account number: " << endl;
  52. cin >> accountNumber;
  53. // Initialize binary search positions
  54. first = 0;
  55. last = SIZE - 1;
  56. // Search the sorted array using binary search
  57. while (first <= last)
  58. {
  59. middle = (first + last) / 2;
  60. if (accountNumbers[middle] == accountNumber)
  61. {
  62. isValid = true;
  63. break;
  64. }
  65. else if (accountNumbers[middle] > accountNumber)
  66. {
  67. last = middle - 1;
  68. }
  69. else
  70. {
  71. first = middle + 1;
  72. }
  73. }
  74. // Display whether the account number is valid
  75. if (isValid)
  76. {
  77. cout << "The account number is valid." << endl;
  78. }
  79. else
  80. {
  81. cout << "The account number is invalid." << endl;
  82. }
  83. return 0;
  84. }
Success #stdin #stdout 0s 5336KB
stdin
5658845
stdout
Enter a charge account number: 
The account number is valid.