Program to search a number using Linear Search
Linear search checks each element in the array one by one until the desired element is found or the array ends.
Steps:
-
Start from the first element.
-
Compare the current element with the key (number to be searched).
-
If it matches, return its position (index).
-
If not, move to the next element.
-
If the end of the array is reached without a match, the element is not present.
Example:
Array: [4, 8, 15, 16, 23, 42]
Key: 23
-
Compare
4→ No match -
Compare
8→ No match -
Compare
15→ No match -
Compare
16→ No match -
Compare
23→ Match found at index4(or position5if counting from 1).
#include<iostream.h>
main()
{
int n, a[20],ser,i,flag=0;
count<<"Enter the size of an array:";
cin>>n;
count<<"Enter the elements to array:\n";
for(i=0; i<n; i++) cin>>a[i];
cout<<"\n Enter the elents to search:";
cin>>ser;
for(i=0; i<n; i++)
{
if(ser == a[i])
{
flag = 1;
break;
}
}
if(flag == 1)
cout<<"\n Element "<<ser<<"is found in the array\n";
else cout<<"\n Element "<<ser<<"is not found in the array\n";
return (0);
}
OUTPUT Enter the size of an array: 5 Enter the elements to array: 1 4 6 9 7 Enter the element to search: 9 Element 9 is found in the array ----- Enter the size of an array: 4 Enter the elements to array: 9 5 7 3 Enter the element to search: 4 Element 4 is not found in the array


