CPP
CPP Notes
To search any element present inside the array in C++ programming using linear search technique, you have ask to the user to enter the array size and array elements to store the elements in the array.
To check/search for the element, just compare with the number to each element present in the array if any element equal to the entered number then print the exact position of the number in the array as shown here in the following program.
#include<conio.h>
void main()
{
clrscr();
int arr[10], i, num, n, c=0, position;
cout<<"Enter the Size of Array :\n ";
cin>>n;
cout<<"Enter"<<n<<" Elements of Array :\n ";
for(i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter the Number to be Search :\n ";
cin>>num;
for(i=0; i<n; i++)
{
if(arr[i]==num)
{
c=1;
position=i+1;
break;
}
}
if(c==0)
{
cout<<"Number not found in Array...!";
}
else
{
cout<<num<<" Found at"<< position <<"Position";
}
getch();
}
2. O/p when element not found
Linear Search in C++
08 July
0
Linear Search in C++ :-
Linear search is used on a collections of items. It relies on the technique of traversing a list from start to end by exploring properties of all the elements that are found on the way. It is the way of searching and possibly the simplest method is the sequential search with an array. This searching method is applicable when data stored in array.To search any element present inside the array in C++ programming using linear search technique, you have ask to the user to enter the array size and array elements to store the elements in the array.
To check/search for the element, just compare with the number to each element present in the array if any element equal to the entered number then print the exact position of the number in the array as shown here in the following program.
C++ Program for Linear Search :-
#include<iostream.h>#include<conio.h>
void main()
{
clrscr();
int arr[10], i, num, n, c=0, position;
cout<<"Enter the Size of Array :\n ";
cin>>n;
cout<<"Enter"<<n<<" Elements of Array :\n ";
for(i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter the Number to be Search :\n ";
cin>>num;
for(i=0; i<n; i++)
{
if(arr[i]==num)
{
c=1;
position=i+1;
break;
}
}
if(c==0)
{
cout<<"Number not found in Array...!";
}
else
{
cout<<num<<" Found at"<< position <<"Position";
}
getch();
}
OutPut :-
1. O/p when Element Found2. O/p when element not found
Must Read :-
Previous article
Next article
Leave Comments
Post a Comment