C++ program for linear search

In this example, you will learn a c++ program for the linear search algorithm. This program finds the position of the target value by comparing it with each element of an array.

Prerequisite

Example 1: C++ program for linear search

//C++ program for linear search
#include<iostream>
using namespace std;
int main()
{
int arrayList[10], i, number, maxNumber, count=0;
cout<<"Enter Maximum number size: ";
cin>>maxNumber;
cout<<"Enter all the numbers:"<<endl;
for(i=0; i<maxNumber; i++)
{
cin>>arrayList[i];
}
cout<<"Search number from the list: ";
cin>>number;
for(i=0; i<maxNumber; i++)
{
if(arrayList[i]==number)
{
count=1;

break;
}
}
if(count==0)
{
cout<<"Number not found.";
}
else
{
cout<<number<<" Found at the list:";
}
return 0;
}

Output

Enter Maximum number size: 3
Enter all the numbers:
5
7
9
Search number from the list: 7
7 Found at the list.

Description and working of this program

  • Take the total number of array elements and their values from the user like 5, 7, 9
  • Ask the user to enter the element for search.  Search =7
  • In liner search, the target element starts comparing with each element of an array and begins from the leftmost side till the exact match.
  • If the target value matches any element of an array program returns its index value.
  • End