This Program will Takes 3 inputs
- For the size of array
- Input for arrays
- Element to be searched in array
If element is available it will return index else -1.
#include <stdio.h>
#define MAX 50
int LinearSearch(int arr[],int n,int item);
int main(void)
{
int i,n,item,arr[MAX],index;
printf("Enter the number of elements : ");
scanf("%d",&n);
printf("Enter the elements : \n");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);
printf("Enter the item to be searched : ");
scanf("%d", &item);
index=LinearSearch(arr,n,item);
if(index==-1)
printf("%d not found in array\n",item);
else
printf("%d found at position %d\n",item,index);
return 0;
}
int LinearSearch(int arr[],int n,int item)
{
int i=0;
while(i<n && item!=arr[i])
i++;
if(i<n)
return i;
else
return -1;
}
Output
Enter the number of elements : 7
Enter the elements :
12 13 14 15 16 17 18
Enter the item to be searched : 13
13 found at position 1