Pages

Friday, 3 July 2015

Linear search an element

C Program to Search an element in Array

Coding:

#include<stdio.h>
#include<stdlib.h>
int main()
{
float *a,s;
int n,i,index;
printf("Please enter total number of elements:");
scanf("%d",&n);
a=(float*)malloc(n*sizeof(float));
for(i=0;i<n;i++)
{
printf("Enter element %d:",i+1);
scanf("%f",&a[i]);
}
printf("Please enter the search element:");
scanf("%f",&s);
for(i=0;i<n;i++)
{
if(a[i]==s)
{
index=i;
break;
}
}
if(i==n)
printf("item not found");
else
printf("%f found at index %d",a[i],index);
return 0;
}

Output:
Please enter total number of elements:4
Enter element 1:10
Enter element 2:20
Enter element 3:30
Enter element 4:40
Please enter the search element:15
item not found