fork download
  1. //Maxwell Brewer CS1A Chapter 8, p. 487, #4
  2. //
  3. /*******************************************************************************
  4.  * VALIDATE CHARGE ACCOUNT (MODIFIED)
  5.  * _____________________________________________________________________________
  6.  * This program checks if a user-entered account number exists in a predefined
  7.  * list using sorting and binary search.
  8.  * _____________________________________________________________________________
  9.  * INPUT
  10.  * user : The account number entered by the user
  11.  *
  12.  * OUTPUT
  13.  * Displays whether the entered number is valid or not.
  14.  *******************************************************************************/
  15.  
  16. #include <iostream>
  17. using namespace std;
  18.  
  19. const unsigned SIZE = 18;
  20.  
  21. int binarySearch(int, const int*, const unsigned);
  22. void selectionSort(int*, const unsigned);
  23.  
  24. int main() {
  25. int accounts[SIZE] = {
  26. 5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
  27. 8080152, 4562555, 5552012, 5050552, 7825877, 1250255,
  28. 1005231, 6545231, 3852085, 7576651, 7881200, 4581002
  29. };
  30.  
  31. int user; // User-entered account number
  32. cout << "Enter your account number: ";
  33. cin >> user;
  34.  
  35. selectionSort(accounts, SIZE); // Sort the array
  36.  
  37. if (binarySearch(user, accounts, SIZE) < 0) {
  38. cout << "Sorry, but the account number is invalid.\n";
  39. } else {
  40. cout << "The account number is valid.\n";
  41. }
  42.  
  43. return 0;
  44. }
  45.  
  46. void selectionSort(int accounts[], const unsigned SIZE) {
  47. int smallest, temp;
  48.  
  49. for (unsigned i = 0; i < SIZE - 1; i++) {
  50. smallest = i;
  51.  
  52. for (unsigned j = i + 1; j < SIZE; j++) {
  53. if (accounts[j] < accounts[smallest]) {
  54. smallest = j;
  55. }
  56. }
  57.  
  58. // Swap the smallest element with the current element
  59. temp = accounts[smallest];
  60. accounts[smallest] = accounts[i];
  61. accounts[i] = temp;
  62. }
  63. }
  64.  
  65. int binarySearch(int account, const int accounts[], const unsigned SIZE) {
  66. int first = 0, last = SIZE - 1, mid;
  67.  
  68. while (first <= last) {
  69. mid = (first + last) / 2;
  70.  
  71. if (account == accounts[mid]) {
  72. return mid; // Return the index of the found account
  73. } else if (account < accounts[mid]) {
  74. last = mid - 1;
  75. } else {
  76. first = mid + 1;
  77. }
  78. }
  79.  
  80. return -1; // Return -1 if not found
  81. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Enter your account number: Sorry, but the account number is invalid.