Home About Contact Privacy Terms Disclaimer
TECHAntena
Last Updated On: June 18, 2016
Editor: Adeeb C

C++ program to search an element in an array using Linear Search

Category: C++,Programing
Tags

Aim:

To write a program to search an element in an array using linear search.

Algorithm:

LINEAR(DATA, N, ITEM, LOC)

Here DATA is a linear array with N elements, and ITEM is a given item of information. This algorithm finds the location LOC of ITEM in DATA, or sets LOC : = if the search is unsuccessful.

 1.    [Insert ITEM at the end of DATA ]. Set DATA[N+1] : = ITEM.

  1.     [Initialize counter.] Set LOC:= 1.

  2.     [Search for ITEM.]

         Repeat while DATA[LOC] != ITEM:

      Set LOC : = LOC + 1.

[End of loop]

4.    [Successful?] If LOC = N + 1, then: Set LOC : =0.

5.    Exit.

Program code:

#include<iostream.h>

#include<conio.h>

class linear

{

int a[20],i,n,item,f;

public:

void getdata()

{

cout<<"Enter the number of elements : ";

cin>>n;

cout<<"Enter the elements : ";

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

{

cin>>a[i];

}

cout<<"Enter the number to search : ";

cin>>item;

}

void search()

{

f=0;

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

{

if(a[i]==item)

{

f=1;

break;

}

}

if(f==1)

cout<<"\nElement found at posistion "<<i+1;

else

cout<<"\nElement not found ";

}

};

void main()

{

clarscr();

linear l;

l.getdata();

l.search();

getch();

}

Output:

Enter the number of elements : 4

Enter the elements : 1 2 3 4

Enter the number to search : 3

Element found at position 3