Linear search in C++
In C++, we can search a number in an
array using linear search and binary search. In linear search algorithm, we
compare number to every element of an array using for statement and
if-else statement. Linear search can take long time for searching because it
compares number to every individual element of an array.
C++ Program for Linear Search
#include<iostream>
using namespace std;
int main()
{
int
arr[10],s,i,l,flag=0;
cout<<"Enter
the length of an array : ";
cin>>l;
for(i=0;i<l;i++)
{
cout<<endl<<"Enter the value of element no
"<<i+1<<" : ";
cin>>arr[i];
}
cout<<endl<<"Enter the value to be search : ";
cin>>s;
for(i=0;i<l;i++)
{
if(arr[i]==s)
{
cout<<endl<<s<<" is present in array at element
no "<<i+1;
flag=1;
break;
}
}
if(flag==0)
{
cout<<endl<<s<<" is not present in array";
}
return 0;
}
OUTPUT 1:
Enter the length of an array : 5
Enter the value of element no 1 : 8
Enter the value of element no 2 : 4
Enter the value of element no 3 : 6
Enter the value of element no 4 : 7
Enter the value of element no 5 : 2
Enter the value to be search : 7
7 is present in array at element no 4
OUTPUT 2:
Enter the length of an array : 5
Enter the value of element no 1 : 5
Enter the value of element no 2 : 6
Enter the value of element no 3 : 1
Enter the value of element no 4 : 2
Enter the value of element no 5 : 3
Enter the value to be search : 10
10 is not present in array
0 comments:
Post a Comment