1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
//Searches a partially filled array of nonnegative integers.
#include <iostream>
using namespace std;
const int DECLARED_SIZE = 20;
void fillArray(int a[], int size, int& numberUsed);
//Precondition: size is the declared size of the array a.
//Postcondition: numberUsed is the number of values stored in a.
//a[0] through a[numberUsed-1] have been filled with
//nonnegative integers read from the keyboard.
int search(const int a[], int numberUsed, int target);
//Precondition: numberUsed is <= the declared size of a.
//Also, a[0] through a[numberUsed -1] have values.
//Returns the first index such that a[index] == target,
//provided there is such an index; otherwise, returns -1.
int main()
{
int arr[DECLARED_SIZE], listSize, target;
fillArray(arr, DECLARED_SIZE, listSize);
char ans, n, N;
int result;
do
{
cout << "Enter a number to search for: ";
cin >> target;
result = search(arr, listSize, target);
if (result == -1)
cout << target << " is not on the list.\n";
else
cout << target << " is stored in array position "
<< result << endl
<< "(Remember: The first position is 0.)\n";
cout << "Search again?(y/n followed by Return): ";
cin >> ans;
} while ((ans != n) && (ans != N));
cout << "End of program.\n";
return 0;
}
void fillArray(int a[], int size, int& numberUsed)
{
cout << "Enter up to " << size << " nonnegative whole numbers.\n"
<< "Mark the end of the list with a negative number.\n";
int next, index = 0;
cin >> next;
while ((next >= 0) && (index < size))
{
a[index] = next;
index++;
cin >> next;
}
numberUsed = index;
}
int search(const int a[], int numberUsed, int target)
{
int index = 0;
bool found = false;
while ((!found) && (index < numberUsed))
if (target == a[index])
found = true;
else
index++;
if (found)
return index;
else
return -1;
}
|