Linear Search Program in C++

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:
LSEARCH
You can download the program:download
If you have any doubts you can make a comment

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C++ and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Linear Search Program in C++

  1. Pingback: Binary Search Program in C++ | letusprogram....!!!

  2. Raj says:

    Good job!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s