Linear Search Program without class
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10],i,n,x,flag=0;
clrscr();
cout<<"Enter the size"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
cout<<"Enter the element to search"<<endl;
cin>>x;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
flag=1;
break;
}
}
if(flag)
cout<<"\n Element "<<x<<" is found at position "<<i+1;
else
cout<<"\n Element "<<x<<" not found";
getch();
}
#include<conio.h>
void main()
{
int a[10],i,n,x,flag=0;
clrscr();
cout<<"Enter the size"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
cout<<"Enter the element to search"<<endl;
cin>>x;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
flag=1;
break;
}
}
if(flag)
cout<<"\n Element "<<x<<" is found at position "<<i+1;
else
cout<<"\n Element "<<x<<" not found";
getch();
}
Linear Search Program with class
#include<iostream.h>
#include<conio.h>
class lsearch
{
public:
int a[10],i,n,x,flag;
public:
void getdata();
void search();
};
void lsearch::getdata()
{
cout<<"Enter the size"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
}
void lsearch::search()
{
cout<<"Enter the element to be searched"<<endl;
cin>>x;
flag=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
flag=1;
break;
}
}
if(flag)
cout<<"Element "<<x<< "found at position "<<i+1;
else
cout<<"Element "<<x<<"not found";
}
void main()
{
lsearch lse;
clrscr();
lse.getdata();
lse.search();
getch();
}
#include<conio.h>
class lsearch
{
public:
int a[10],i,n,x,flag;
public:
void getdata();
void search();
};
void lsearch::getdata()
{
cout<<"Enter the size"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
}
void lsearch::search()
{
cout<<"Enter the element to be searched"<<endl;
cin>>x;
flag=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
flag=1;
break;
}
}
if(flag)
cout<<"Element "<<x<< "found at position "<<i+1;
else
cout<<"Element "<<x<<"not found";
}
void main()
{
lsearch lse;
clrscr();
lse.getdata();
lse.search();
getch();
}
Linear search Program with Address --- Array --- Data
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class linearsearch
{
public:
int a[10],i,n,item,flag;
public:
void getdata();
void search();
};
void linearsearch::getdata()
{
cout<<"Enter the size"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for(i=0;i<n;i++)
{
cout<<"Element a["<<i<<"] :"<<ends;
cin>>a[i];
}
cout<<"\nAddress"<<setw(25)<<"Array"<<setw(12)<<"Data"<<endl;
for(i=0;i<n;i++)
{
cout<<"\nAddress:"<< &a[i] <<"\tArray:"<<"a["<<i<<"]"<<"\tData:"<<a[i];
cout<<"\n";
}
}
void linearsearch::search()
{
cout<<"Enter the element to be searched"<<endl;
cin>>item;
flag=0;
for(i=0;i<n;i++)
{
if(a[i]==item)
{
cout<<"Element "<<item<< "found at position "<<i+1;
flag=1;
break;
}
}
if(flag==0)
cout<<"Element "<<item<<"not found in the array";
}
void main()
{
linearsearch ls;
clrscr();
ls.getdata();
ls.search();
getch();
}
Output:
https://www.youtube.com/watch?v=PDE8pCQ9Tz4
No comments:
Post a Comment