This Post Contains A C++ Program To Perform Linear Search. With Correct Source Code & Output. This Program Is Written, Compiled & Executed At TurboC/C++3.0 Compiler & Will Help You To Understand The Concept Of 'Linear Search' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.
# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.
C++ Program To Perform Linear Search.
/* Declaration Of Header Files */
#include<iostream.h>
#include<conio.h>
/* Start Of Main Program */
void main()
{
/* Declaration Of Variables */
int i, j, x, dim, t;
int a[20];
clrscr();
// Accepting Range Of Array From User.
cout<<" \n Enter Dimension For Array : ";
cin>>dim;
// Accepting Value For Array From User.
cout<<" \n Enter The Values For Array A : ";
for(i=0;i<dim;i++)
{
cin>>a[i];
}
// For Searching Values, They Should Be Sorted First.
// Sorting Values In Ascending Order.
for(i=0;i<dim;i++)
{
for(j=i+1;j<dim;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
// Printing Values Of Array 'a' After Sorting.
cout<<" \n Sorted Array Is : ";
for(i=0;i<dim;i++)
{
cout<<a[i]<<"\t";
}
/* Source Code For Computing Linear Search */
cout<<" \n Enter Value To Be Searched : ";
cin>>x;
for(i=0;i<dim;i++)
{
if(x==a[i])
{
cout<<"\n"<<x<<" Is Located At Location "<<i+1;
}
}
getch();
}
/* End Of Main Program */
Output :
Enter Dimension :5
Enter 5 Values For Array 'a' :
4 2 5 1 3
Sorted Array 'a' Is :
1 2 3 4 5
Enter Value To Be Searched : 2
2 Is Located At Location 2.
# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.
C++ Program To Perform Linear Search.
/* Declaration Of Header Files */
#include<iostream.h>
#include<conio.h>
/* Start Of Main Program */
void main()
{
/* Declaration Of Variables */
int i, j, x, dim, t;
int a[20];
clrscr();
// Accepting Range Of Array From User.
cout<<" \n Enter Dimension For Array : ";
cin>>dim;
// Accepting Value For Array From User.
cout<<" \n Enter The Values For Array A : ";
for(i=0;i<dim;i++)
{
cin>>a[i];
}
// For Searching Values, They Should Be Sorted First.
// Sorting Values In Ascending Order.
for(i=0;i<dim;i++)
{
for(j=i+1;j<dim;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
// Printing Values Of Array 'a' After Sorting.
cout<<" \n Sorted Array Is : ";
for(i=0;i<dim;i++)
{
cout<<a[i]<<"\t";
}
/* Source Code For Computing Linear Search */
cout<<" \n Enter Value To Be Searched : ";
cin>>x;
for(i=0;i<dim;i++)
{
if(x==a[i])
{
cout<<"\n"<<x<<" Is Located At Location "<<i+1;
}
}
getch();
}
/* End Of Main Program */
Output :
Enter Dimension :5
Enter 5 Values For Array 'a' :
4 2 5 1 3
Sorted Array 'a' Is :
1 2 3 4 5
Enter Value To Be Searched : 2
2 Is Located At Location 2.
No comments:
Post a Comment