Wednesday, 24 September 2014

Linear Search

PROGRAM:

#include<iostream>
int a[10],i,n,key,f=0;
class linear
{
            public:
            void getdata()
            {
                        cout<<"Enter the array limit:\t";
                        cin>>n;
                        cout<<"Enter array elements:\n";
                        for(i=0;i<n;i++)
                        {
                                    cin>>a[i];
                        }
                        cout<<"Enter the element to be searched:\t";
                        cin>>key;
            }
            void search()
            {
                        for(i=0;i<n;i++)
                        {
                                    if(a[i]==key)
                                    {
                                                cout<<"Element found\n";
                                                f=1;
                                                break;
                                    }
                        }
                        if(f==0)
                        {
                                    cout<<"Element not found\n";
                        }
            }
};

 void main()
{
    linear ls;
    cout<<"\n\n LINEAR SEARCH \n\n";
    ls.getdata();
    ls.search();
}


OUTPUT:

LINEAR SEARCH

Enter the array limit:  5
Enter array elements:
1
3
5
7
9
Enter the element to be searched:       9
Element found

 
LINEAR SEARCH

Enter the array limit:  5
Enter array elements:
2
4
6
8
10
Enter the element to be searched:       9
Element not found

No comments:

Post a Comment