C Program to Execute Linear Search

General Introduction:

Linear search is a searching technique where an element that is to be searched is searched linearly or sequentially.

  • The element to be searched is searched from the left-most index of the array where elements are stored.
  • The element is searched until the element is found, or the search index runs out of the element of an array.
  • If the searched element is found, the message is displayed as “The element is found at index found.”
  • However, if the elements are not found even after scanning all the elements in an array then, the message “The element not found” is displayed.

Code in C:

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

void linear_search(int[],int,int);
int main()
{
	int a[20],n;
	int key;
	int i;
	printf("How many numbers you want to insert: ");
	scanf("%d",&n);
	
	for(i=0;i<n;i++)
	{
		printf("\nEnter %dth item: ",i+1);
		scanf("%d",&a[i]);
	}
	
	printf("\nEnter the item you want to linear search:");
	scanf("%d",&key);
	linear_search(a,n,key);
	getch();
	return(0);
	
}

void linear_search(int a[],int n,int key)
{
	int i;
	for(i=0;i<n;i++)
	{
		if(key==a[i])
		{
			printf("The element %d is found in %d index",key,i+1);
			break;
		}
	}
	
	if(i==n)
	{
		printf("The searched element %d is not found",key);
	}
}

Outputs:

C Program to Execute Linear Search 1
When the searched element is found.
C Program to Execute Linear Search 2
When the searched element is not found.

Do comment if you are confused in any steps.

Also Read: Recursive Program to find the nth term in Fibonacci Series

LEAVE A REPLY

Please enter your comment!
Please enter your name here