C++ Program for Linear Search

Linear search is method to find an element in an array. When you enter an array element it can compare the array elements separately by the given element. If it matches then its find the location of the element.

Only disadvantage in this algorithm is time complexity. It takes more time to check the elements for larger arrays. Binary search is also one of the method to find an element and its location. The array elements must be sorted in binary search.

C++ Program for Linear Search

C++ Program for Linear Search

#include<iostream>
 
using namespace std;
 
int main()
{
int a[20],n,x,i,flag=0;
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter elements of the array\n";
for(i=0;i<n;++i)
cin>>a[i];
cout<<"\nEnter element to search:";
cin>>x;
for(i=0;i<n;++i)
{
if(a[i]==x)
{
flag=1;
break;
}
}
if(flag)
cout<<"\nElement is found at position "<<i+1;
else
cout<<"\nElement not found";
return 0;
}

Compared to binary search linear search algorithm is best to find an element and its location. if condition uses to find the element and its location in the above program. if it is true then it finds the location of the element.

Read Also : C++ Program to Print Prime Numbers

Output

How many elements?4

Enter elements of the array
5 9 12 4

Enter element to search:9

Element is found at position 2

Final Words

I hope this article helps you to find Linear Search in C++ Program. If you face any issues please let me know via the comment section. Share this article with other C++ program developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment