In this tutorial we shall learn about searching elements present in the array.Generally two methods are being followed for searching.Those are:
1.Linear searching
2.Binary searching
.In this tutorial we shall learn about Linear searching.
Method:
1.Get the data from the user in an array.
2.Ask the user to enter an element to search in the array.
3.Compare the given key element to each and every element in array
4.If element is present in the given array, then display the position of the element.
Let us write the code for it.
#include<iostream.h> #include<conio.h> class lsearch { public: int data[10],n,key; void getdata(); void display(); }; void lsearch :: getdata() { cout<<"\nEnter the length of the array:"; cin>>n; for(int i=0;i<n;i++) { cout<<"\nEnter the element in the "<<(i+1)<<" position of the array:"; cin>>data[i]; } cout<<"\nEnter the key to find the element in the array:"; cin>>key; } void lsearch :: display() { int flag=0; for(int i=0;i<n;i++) { if(key == data[i]) { cout<<"\n\nThe element "<<key<<" is present in the position "<<(i+1)<<" of the array"; flag++; } } if(flag==0) cout<<"\nGiven key "<<key<<" is not present in the array"; } void main() { clrscr(); lsearch ob; ob.getdata(); ob.display(); getch(); }
OUTPUT:
You can download the program:download
If you have any doubts you can make a comment
Pingback: Binary Search Program in C++ | letusprogram....!!!
Good job!