Written by Sai Sandeep Thota on January 12, 2013 in C > Programming

C Program to Implement Linear Search

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Linear Search is a searching technique which is used to search an element in an Array. We are going to write this program in C language for now, The program run time will be more if the elements in the array are more and vice-versa. Linear search will have a time complexity of O(n). We are using a separate function for searching a element as it makes the program more easy to understand.

In the main function we are collecting the information needed like Size of the Array, Array Elements and Key element to be searched and we are calling the lsearch function. With a for loop, we are iterating an if condition for checking the occurrence of key element.

#include<conio.h>
#include<stdio.h>

void lsearch(int[], int, int);

void main()
{
	int elements[100], size, key, i;
	clrscr();
	printf("\nEnter Array Size:");
	scanf("%d",&size);
	printf("\nEnter Elements into Elements Array:");
	for(i=0;i<size;i++)
		scanf("%d",&elements[i]);
	printf("\nEnter Key to be searched:");
	scanf("%d",&key);
	lsearch(elements, size, key);
	getch();
}

void lsearch(int elements[], int size, int key)
{
	int i, flag=0;

	for(i=0;i<size;i++)
	{
		if(elements[i]==key)
		{
			flag++;
		}
	}

	if(flag==0)
	{
		printf("\nElement not found!!");
	}
	else
	{
		printf("\nElement: %d has been found %d times", key, flag);
	}

}

Output:
linear-search

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: