C Program to search a key element using linear search using recursion
Program
#include<stdio.h>
int linear_search(int, int, int[]);
void main()
{
int n, a[10], key, position, i;
printf("Enter the size of the array\n");
scanf("%d", &n);
printf("Enter %d integer numbers\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key element to be searched\n");
scanf("%d", &key);
position = linear_search(n, key, a);
if(position != -1)
printf("Key element found at position %d \n", position + 1);
else
printf("Key element not found\n");
}
int linear_search(int n, int key, int a[])
{
if(n < 0)
return -1;
else if(a[n] == key)
return n;
else
return linear_search(n-1, key, a);
}
Output 1
Enter the size of the array
7
Enter 7 integer numbers
22
78
43
40
87
56
10
Enter the key element to be searched
87
Key element found at position 5
Output 2
Enter the size of the array
6
Enter 6 integer numbers
123
20
230
11
45
6
Enter the key element to be searched
90
Key element not found