/* Array search for a target value in an array */ #include #define NSIZE 20 #define NOT_FOUND -1 int search(const int arr[], int target, int n); int main() { int array[NSIZE], size, value, position; int i, num; FILE *fp; fp = fopen("data.txt", "r"); size = 0; while(fscanf(fp, "%d", &num) == 1) array[size++] = num; printf("The data array is = "); for (i=0; i "); scanf("%d", &value); while(value != -1) { position = search(array, value, size); if(position == -1) printf("%d is not in the array.\n", value); else printf("%d is located at position %d in the array.\n", value, position); printf("\nPlease enter a value (-1 = done)> "); scanf("%d", &value); } fclose(fp); return 0; } /* Searches for target item in first n elements of array arr */ int search(const int arr[], int target, int n) { int i, found = 0, where; i = 0; while (!found && i < n) { if (arr[i] == target) found = 1; else ++i; } if (found) where = i; else where = NOT_FOUND; return (where); }