Design a program using one-dimensional array that demonstrates the concept of linear search. The program will ask the user how many elements will be processed, and the program will ask the user to give a series of numbers. The program will ask the user to enter a number to be searched. If the given number is in the list, the program will display the number and identify the exact location where the number is located. The program will also display No Number Found when the number is not given in the list.
#include<iostream>
#include<string>
using namespace std;
int main()
{
do
{
int N,search;
bool searched=false;//indicator of finding element
cout<<"\nHow many elements will be processed?\n"
<<"Your enter (0 - exit program): ";
cin>>N;
if(N<=0)break;
int* arr=new int[N];//allocate memory for array
for(int i=0;i<N;i++)
{
cout<<"Please enter a value for element ["<<i<<"]: ";
cin>>arr[i];
}
cout<<"Please enter a value to be searched: ";
cin>>search;
int j;
for(j=0;j<N;j++)
{
if(arr[j]==search)
{
searched=true;
break;
}
}
if(searched)
{
cout<<"The value "<<search<<" is found at "<<j<<" position";
}
else
{
cout<<"No Number Found";
}
delete[] arr;//free meemory
}while(true);
}
Comments
Leave a comment