Linear search

The following program takes a number as an input and checks whether that number is present in a group of elements or not. It takes linear time to execute. The program is implemented using c.

#include<stdio.h>
int main()
{
int n;
printf("Enter number of elements of the group : ");
scanf("%d",&n);
int a[n],m,i;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("nEnter a element for searching : ");
scanf("%d",&m);
for(i=0;i<n;i++)
{
if(m==a[i])
{
printf("%d found in %d position.",m,i+1);
break;
}
}
return 0;
}

Description :

In the above program the group of elements are stored using array. Then the input number is compared with all the elements in the array. If input number and element of array are equal, then it prints found and terminates.

Output:

Enter number of elements : 5
9 6 7 2 8
Enter a element for searching : 7
7 found in 3 position


Related posts

Leave a Comment