Question
The code of a function that searches for a target value in an array is given below. Assume the target has not been found. Start
The code of a function that searches for a target value in an array is given below. Assume the target has not been found. Start with the initial array element. repeat while the target is not found and there are more array elements if the current element matches the target Set a flag to indicate that the target has been found else Advance to the next array element. if the target was found Return the target index as the search result else Return -1 as the search result.
____________________________________________________________________ /* Figure 7.14 Function That Searches for a Target Value in an Array */ #define NOT_FOUND -1 /* Value returned by search function if target not found */
/* * Searches for target item in first n elements of array arr * Returns index of target or NOT_FOUND * Pre: target and first n elements of array arr are defined and n>=0 */ int search(const int arr[], /* input - array to search */ int target, /* input - value searched for */ int n) /* input - number of elements to search */ { int i, found = 0, /* whether or not target has been found */ where; /* index where target found or NOT_FOUND */
/* Compares each element to target */ i = 0; while (!found && i < n) { if (arr[i] == target) found = 1; else ++i; }
/* Returns index of element matching target or NOT_FOUND */ if (found) where = i; else where = NOT_FOUND;
return (where); }
C language
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started