In this example, you will learn the 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.
if there are six elements in an array i.e 5, 7, 2, 1,3, and 9. The user asks to find 1. The program compares each and every value in the array in sequential order until found the target value which is “1”. if found displays the message” found at the list” otherwise shows “number is not found”. Check the program below.
Example 1: Linear search program in C++
//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;
}