C++ program to implement Linear Search

#include<iostream>
using namespace std;
int linearsearch(int *array,int key,int n);

 

int main()

{

             int *arr,n,key;

             cout<<"Enter how many elements :";

             cin>>n;

             arr=new int[n];

             cout<<endl<<"Enter elements : ";

             for(int i=0;i<n;i++)

             cin>>arr[i];

             cout<<endl<<"Enter the element to search : ";

             cin>>key;

             int r=linearsearch(arr,key,n);

             if(r)

             cout<<endl<<"element found at"<< r+1<<"position";

             else cout<<endl<<"Element not found";

             return 0;

}

int linearsearch(int *arr,int key,int n)

{

             int flag=0;

             for(int i=0;i<n;i++)

             {

                          if(key==arr[i])

                          {

                              flag=1;

                              break;

                          }

             }

             if(flag)

             return i;

             else return 0;

}

Input

Enter how many elements: 8

Enter elements : 23   12  25  99  77  56   1   2

Enter the element to search: 99

Output

element found at 4  position

Leave a comment

Your email address will not be published. Required fields are marked *