1-dimensional Array Exercise (easy) Linear Search Parameters: A - An array of in
ID: 3778682 • Letter: 1
Question
1-dimensional Array Exercise (easy) Linear Search Parameters: A - An array of integers n - The length of A k - An integer to search for in A Return Value: If k is an element of A, the return value should be an integer i such that A[i] == k. If k is not an element of A, the return value should be the constant NOT_FOUND (which is defined at the top of this file to be -1). ================================================== */ int linear_search(int A[], int n, int k){ /* ... Your code here ... */ return NOT_FOUND; } /* linear_search */
Explanation / Answer
#include<stdio.h>
#define NOT_FOUND -1
int linear_search(int A[], int n, int k);
int main()
{
int arr[10]={2,5,8,9,11,23,56,7,12,3};
int ret;
if( (ret = linear_search(arr,10,23) )< 0 )
{
printf("Element not found ");
}
else
{
printf("Element found at position %d ",ret+1);
}
}
int linear_search(int A[], int n, int k)
{
int FOUND ;
/* ... Your code here ... */
for( int i = 0; i < n ; i++)
{
if( A[i] == k )
{
FOUND = i;
return FOUND;
}
}
return NOT_FOUND;
} /* linear_search */
-------------------------------------------------
for the array arr[10]={2,5,8,9,11,23,56,7,12,3}, got output below...
Element 23 found at position 6
Element 0 is not found
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.