C Program to search a key element using Linear Search using Functions
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 == 0)
printf("Key element not found\n");
else
printf("Key element found at position %d \n", position);
}
int linear_search(int n, int key, int a[])
{
int flag, i;
for(i = 0; i < n; i++)
{
if(key == a[i])
{
flag = i + 1;
break;
}
else
flag = 0;
}
return flag;
}
Output 1
Enter the size of the array
5
Enter 5 integer numbers
58
11
34
20
78
Enter the key element to be searched
34
Key element found at position 3
Output 2
Enter the size of the array
6
Enter 6 integer numbers
10
93
21
12
56
88
Enter the key element to be searched
4
Key element not found