Problem:1
In this code if I search a number which is not in array it should display Value not found
but I don't know it's not displaying that message instead everytime it's showing Found value in element -5
I don't have any clue why it's happening.
#include<stdio.h>
#define SIZE 100
size_t linearSearch(const int array[], int key, size_t size);
int main(void)
{
int a[SIZE];
size_t x;
int searchKey;
size_t element;
for(x=0; x<SIZE; ++x){
a[x] = 2*x;
}
for(x=0; x<SIZE; ++x){
if(x%10 == 0){
puts("");
}
printf("%5d", a[x]);
}
puts("\n\nEnter integer search key:");
scanf("%d", &searchKey);
// attempt to locate searchKey in array a
element = linearSearch(a, searchKey, SIZE);
// display results
if(element != -1){
printf("Found value in element %d", element);
}
else{
puts("Value not found");
}
}
size_t linearSearch(const int array[], int key, size_t size)
{
if(size<0){
return -1;
}
if(key == array[size-1]){
return size-1;
}
return linearSearch(array, key, size-1);
}
Problem:2
I can't understood how
size_t linearSearch(const int array[], int key, size_t size)
function working specially these line
if(key == array[size-1]){
return size-1;
return linearSearch(array, key, size-1);