Linear or Sequential Search

Program In C++:-
                           //Linear Search
#include <iostream>
using namespace std;
int LinearSearch(int a[],int key,int n)
{
    for(int i=0;i<n;i++)
    {
        if(a[i]==key)
        {
            return i+1;
        }
    }
    return 0;
}
int main()
{
    int n,key,index;
    cout<<"Enter the size of array:";
    cin>>n;
    int a[n];
    cout<<"Enter the values in Array:\n";
    for(int i=0;i<n;i++)
        cin>>a[i];
    cout<<"Enter the element to be searched:";
    cin>>key;
    index=LinearSearch(a,key,n);
    if (index!=0)
        cout<<"Element found at "<<index<<" position";
    else
        cout<<"Not Found";
}
/*
Output
Enter the size of array:3
Enter the values in Array:
1
2
3
Enter the element to be searched:1
Element found at 1 position

*/

Comments